Example usage for android.content Intent getPackage

List of usage examples for android.content Intent getPackage

Introduction

In this page you can find the example usage for android.content Intent getPackage.

Prototype

public @Nullable String getPackage() 

Source Link

Document

Retrieve the application package name this Intent is limited to.

Usage

From source file:net.openid.appauth.AuthorizationService.java

/**
 * Sends an authorization request to the authorization service, using a
 * [custom tab](https://developer.chrome.com/multidevice/android/customtabs).
 * The parameters of this request are determined by both the authorization service
 * configuration and the provided {@link AuthorizationRequest request object}. Upon completion
 * of this request, the provided {@link PendingIntent completion PendingIntent} will be invoked.
 * If the user cancels the authorization request, the provided
 * {@link PendingIntent cancel PendingIntent} will be invoked.
 *
 * @param customTabsIntent//from  w  w w.  j a  v a 2  s . c o  m
 *     The intent that will be used to start the custom tab. It is recommended that this intent
 *     be created with the help of {@link #createCustomTabsIntentBuilder(Uri[])}, which will
 *     ensure that a warmed-up version of the browser will be used, minimizing latency.
 *
 * @throws android.content.ActivityNotFoundException if no suitable browser is available to
 *     perform the authorization flow.
 */
public void performAuthorizationRequest(@NonNull AuthorizationRequest request,
        @NonNull PendingIntent completedIntent, @Nullable PendingIntent canceledIntent,
        @NonNull CustomTabsIntent customTabsIntent) {
    checkNotDisposed();

    if (mBrowser == null) {
        throw new ActivityNotFoundException();
    }

    Uri requestUri = request.toUri();
    Intent intent;
    if (mBrowser.useCustomTab) {
        intent = customTabsIntent.intent;
    } else {
        intent = new Intent(Intent.ACTION_VIEW);
    }
    intent.setPackage(mBrowser.packageName);
    intent.setData(requestUri);

    Logger.debug("Using %s as browser for auth, custom tab = %s", intent.getPackage(),
            mBrowser.useCustomTab.toString());
    intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.NO_TITLE);

    Logger.debug("Initiating authorization request to %s", request.configuration.authorizationEndpoint);
    mContext.startActivity(AuthorizationManagementActivity.createStartIntent(mContext, request, intent,
            completedIntent, canceledIntent));
}

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private void oldPushNotification(Context context, Intent intent) {
    PushReportUtility.log("oldPushNotification->isForground = " + EBrowserActivity.isForground);
    if (EBrowserActivity.isForground) {
        if (mContext != null) {
            intent.putExtra("ntype", F_TYPE_PUSH);
            ((EBrowserActivity) mContext).handleIntent(intent);
        }//from   w ww  . j av a  2  s  .c o m
    } else {
        CharSequence tickerText = intent.getStringExtra("title"); // ????
        Resources res = context.getResources();
        int icon = res.getIdentifier("icon", "drawable", intent.getPackage());
        long when = System.currentTimeMillis(); // ?
        // ??Nofification

        String notifyTitle = null;
        String pushMessage = intent.getStringExtra("message");
        String value = intent.getStringExtra("data"); // ??json
        try {
            JSONObject bodyJson = new JSONObject(value);
            notifyTitle = bodyJson.getString("msgName");// ?
        } catch (Exception e) {
            PushReportUtility.oe("onReceive", e);
        }
        if (TextUtils.isEmpty(notifyTitle)) {
            notifyTitle = intent.getStringExtra("widgetName");// msgNamewidgetName?
        }
        if (TextUtils.isEmpty(notifyTitle)) {
            notifyTitle = "APPCAN";// widgetNameAPPCAN?
        }
        CharSequence contentTitle = notifyTitle; // ?
        Intent notificationIntent = new Intent(context, EBrowserActivity.class); // ??Activity
        notificationIntent.putExtra("data", value);
        notificationIntent.putExtra("message", pushMessage);
        notificationIntent.putExtra("ntype", F_TYPE_PUSH);
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
        Notification notification = new Notification(icon, tickerText, when);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        if (Build.VERSION.SDK_INT >= 16) {
            try {
                Field priorityField = Notification.class.getField("priority");
                priorityField.setAccessible(true);
                priorityField.set(notification, 1);
            } catch (Exception e) {
                PushReportUtility.oe("onReceive", e);
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(context, notificationNB, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(context, contentTitle, tickerText, contentIntent);
        // NotificationNotificationManager
        mNotificationManager.notify(notificationNB, notification);
        notificationNB++;
    }
}

From source file:com.android.tv.settings.users.AppRestrictionsFragment.java

private void assertSafeToStartCustomActivity(Intent intent, String packageName) {
    // Activity can be started if it belongs to the same app
    if (intent.getPackage() != null && intent.getPackage().equals(packageName)) {
        return;/* w  ww. j  a v a  2  s  .c om*/
    }
    // Activity can be started if intent resolves to multiple activities
    List<ResolveInfo> resolveInfos = AppRestrictionsFragment.this.mPackageManager.queryIntentActivities(intent,
            0 /* no flags */);
    if (resolveInfos.size() != 1) {
        return;
    }
    // Prevent potential privilege escalation
    ActivityInfo activityInfo = resolveInfos.get(0).activityInfo;
    if (!packageName.equals(activityInfo.packageName)) {
        throw new SecurityException(
                "Application " + packageName + " is not allowed to start activity " + intent);
    }
}

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private void buildPushNotification(Context context, Intent intent, PushDataInfo dataInfo) {
    String title = dataInfo.getTitle();
    String body = dataInfo.getAlert();
    String message = dataInfo.getPushDataString();
    Builder builder = new Builder(context);
    builder.setAutoCancel(true);/*from  w  w w .ja v a  2  s  . co m*/
    builder.setContentTitle(title); // 
    builder.setContentText(body); // 
    builder.setTicker(body); // ??

    String[] remindType = dataInfo.getRemindType();
    if (remindType != null) {
        if (remindType.length == 3) {
            builder.setDefaults(Notification.DEFAULT_ALL);
        } else {
            int defaults = 0;
            for (int i = 0; i < remindType.length; i++) {
                if ("sound".equalsIgnoreCase(remindType[i])) {
                    defaults = Notification.DEFAULT_SOUND;
                    continue;
                }
                if ("shake".equalsIgnoreCase(remindType[i])) {
                    defaults = defaults | Notification.DEFAULT_VIBRATE;
                    continue;
                }
                if ("breathe".equalsIgnoreCase(remindType[i])) {
                    defaults = defaults | Notification.DEFAULT_LIGHTS;
                    continue;
                }
            }
            builder.setDefaults(defaults);
        }
    }

    Resources res = context.getResources();
    int icon = res.getIdentifier("icon", "drawable", intent.getPackage());
    builder.setSmallIcon(icon);
    builder.setWhen(System.currentTimeMillis()); // 

    String iconUrl = dataInfo.getIconUrl();
    boolean isDefaultIcon = !TextUtils.isEmpty(iconUrl) && "default".equalsIgnoreCase(iconUrl);
    Bitmap bitmap = null;
    if (!isDefaultIcon) {
        bitmap = getIconBitmap(context, iconUrl);
    }
    String fontColor = dataInfo.getFontColor();
    RemoteViews remoteViews = null;
    if (!TextUtils.isEmpty(fontColor)) {
        int color = BUtility.parseColor(fontColor);
        int alphaColor = parseAlphaColor(fontColor);
        remoteViews = new RemoteViews(intent.getPackage(), EUExUtil.getResLayoutID("push_notification_view"));
        // Title
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_title"), title);
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_title"), color);
        // Body
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_body"), body);
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_body"), alphaColor);
        // LargeIcon
        if (bitmap != null) {
            remoteViews.setImageViewBitmap(EUExUtil.getResIdID("notification_largeIcon"), bitmap);
        } else {
            remoteViews.setImageViewResource(EUExUtil.getResIdID("notification_largeIcon"),
                    EUExUtil.getResDrawableID("icon"));
        }
        // Time
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_time"),
                format.format(System.currentTimeMillis()));
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_time"), alphaColor);
        builder.setContent(remoteViews);
    }

    Intent notiIntent = new Intent(context, EBrowserActivity.class);
    notiIntent.putExtra("ntype", F_TYPE_PUSH);
    notiIntent.putExtra("data", body);
    notiIntent.putExtra("message", message);
    Bundle bundle = new Bundle();
    bundle.putSerializable(PushReportConstants.PUSH_DATA_INFO_KEY, dataInfo);
    notiIntent.putExtras(bundle);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationNB, notiIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = builder.build();
    // Android v4bug2.3?Builder?NotificationRemoteView??
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && remoteViews != null) {
        notification.contentView = remoteViews;
    }
    manager.notify(notificationNB, notification);
    notificationNB++;
}

From source file:org.brandroid.openmanager.fragments.ContentFragment.java

public boolean executeMenu(final int id, final Object mode, final OpenPath file) {
    Logger.LogInfo("ContentFragment.executeMenu(0x" + Integer.toHexString(id) + ") on " + file);
    final String path = file != null ? file.getPath() : null;
    OpenPath parent = file != null ? file.getParent() : mPath;
    if (parent == null || parent instanceof OpenCursor)
        parent = OpenFile.getExternalMemoryDrive(true);
    final OpenPath folder = parent;
    String name = file != null ? file.getName() : null;

    final boolean fromPasteMenu = file.equals(mPath);

    switch (id) {
    case R.id.menu_refresh:
        if (DEBUG)
            Logger.LogDebug("Refreshing " + getPath().getPath());
        getPath().clearChildren();//from   www . j  a  v  a 2  s  . c o  m
        FileManager.removeOpenCache(getPath().getPath());
        getPath().deleteFolderFromDb();
        runUpdateTask(true);
        refreshData(new Bundle(), false);
        return true;

    case R.id.menu_context_download:
        OpenPath dl = OpenExplorer.getDownloadParent().getFirstDir();
        if (dl == null)
            dl = OpenFile.getExternalMemoryDrive(true);
        if (dl != null) {
            List<OpenPath> files = new ArrayList<OpenPath>();
            files.add(file);
            getEventHandler().copyFile(files, dl, getActivity());
        } else
            getExplorer().showToast(R.string.s_error_ftp);
        return true;

    case R.id.menu_context_selectall:
        if (getContentAdapter() == null)
            return false;
        boolean hasAll = true;
        for (OpenPath p : getContentAdapter().getAll())
            if (!getClipboard().contains(p)) {
                hasAll = false;
                break;
            }
        if (!hasAll)
            getClipboard().addAll(getContentAdapter().getAll());
        else
            getClipboard().removeAll(getContentAdapter().getAll());
        return true;

    case R.id.menu_context_view:
        Intent vintent = IntentManager.getIntent(file, getExplorer(), Intent.ACTION_VIEW);
        if (vintent != null)
            getActivity().startActivity(vintent);
        else {
            if (getExplorer() != null)
                getExplorer().showToast(R.string.s_error_no_intents);
            if (file.length() < getResources().getInteger(R.integer.max_text_editor_size))
                getExplorer().editFile(file);
        }
        break;

    case R.id.menu_context_edit:
        Intent intent = IntentManager.getIntent(file, getExplorer(), Intent.ACTION_EDIT);
        if (intent != null) {
            if (intent.getPackage() != null && intent.getPackage().equals(getActivity().getPackageName()))
                getExplorer().editFile(file);
            else
                try {
                    intent.setAction(Intent.ACTION_EDIT);
                    Logger.LogVerbose("Starting Intent: " + intent.toString());
                    getExplorer().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    getExplorer().showToast(R.string.s_error_no_intents);
                    getExplorer().editFile(file);
                }
        } else if (file.length() < getResources().getInteger(R.integer.max_text_editor_size)) {
            getExplorer().editFile(file);
        } else {
            getExplorer().showToast(R.string.s_error_no_intents);
        }
        break;

    case R.id.menu_multi:
        changeMultiSelectState(!getClipboard().isMultiselect());
        if (!fromPasteMenu)
            getClipboard().add(file);
        return true;
    case R.id.menu_context_bookmark:
        getExplorer().addBookmark(file);
        finishMode(mode);
        return true;

    case R.id.menu_context_delete:
        //fileList.add(file);
        getHandler().deleteFile(file, getActivity(), true);
        finishMode(mode);
        if (getContentAdapter() != null)
            getContentAdapter().notifyDataSetChanged();
        return true;

    case R.id.menu_context_rename:
        getHandler().renameFile(file, true, getActivity());
        finishMode(mode);
        return true;

    case R.id.menu_context_copy:
    case R.id.menu_context_cut:
        getClipboard().DeleteSource = id == R.id.menu_context_cut;
        file.setTag(id);
        getClipboard().add(file);
        return true;

    case R.id.menu_context_paste:
    case R.id.content_paste:
        OpenPath into = file;
        if (fromPasteMenu)
            into = mPath;
        if (!file.isDirectory()) {
            Logger.LogWarning("Can't paste into file (" + file.getPath() + "). Using parent directory ("
                    + folder.getPath() + ")");
            into = folder;
        }
        OpenClipboard cb = getClipboard();
        cb.setCurrentPath(into);
        if (cb.size() > 0) {
            if (cb.DeleteSource)
                getHandler().cutFile(cb, into, getActivity());
            else
                getHandler().copyFile(cb, into, getActivity());
            refreshOperations();
        }

        cb.DeleteSource = false;
        if (cb.ClearAfter)
            getClipboard().clear();
        getExplorer().updateTitle(path);
        finishMode(mode);
        return true;

    case R.id.menu_context_zip:
        if (!fromPasteMenu)
            getClipboard().add(file);
        else
            getClipboard().setCurrentPath(mPath);

        getClipboard().ClearAfter = true;
        String zname = getClipboard().get(0).getName().replace("." + file.getExtension(), "") + ".zip";
        if (getClipboard().size() > 1) {
            OpenPath last = getClipboard().get(getClipboard().getCount() - 1);
            if (last != null && last.getParent() != null) {
                if (last.getParent() instanceof OpenCursor)
                    zname = folder.getPath();
                zname = last.getParent().getName() + ".zip";
            }
        }
        final String def = zname;

        final InputDialog dZip = new InputDialog(getExplorer()).setIcon(R.drawable.sm_zip)
                .setTitle(R.string.s_menu_zip).setMessageTop(R.string.s_prompt_path)
                .setDefaultTop(mPath.getPath()).setMessage(R.string.s_prompt_zip).setCancelable(true)
                .setNegativeButton(android.R.string.no, new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (!fromPasteMenu && getClipboard().size() <= 1)
                            getClipboard().clear();
                    }
                });
        dZip.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                if (fromPasteMenu && getClipboard().size() <= 1)
                    getClipboard().clear();
            }
        }).setPositiveButton(android.R.string.ok, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                OpenPath zFolder = new OpenFile(dZip.getInputTopText());
                if (zFolder == null || !zFolder.exists())
                    zFolder = folder;
                OpenPath zipFile = zFolder.getChild(dZip.getInputText());
                Logger.LogVerbose("Zipping " + getClipboard().size() + " items to " + zipFile.getPath());
                getHandler().zipFile(zipFile, getClipboard(), getExplorer());
                refreshOperations();
                finishMode(mode);
            }
        }).setDefaultText(def);
        dZip.create().show();
        return true;

    //case R.id.menu_context_unzip:
    //   getHandler().unzipFile(file, getExplorer());
    //   return true;

    case R.id.menu_context_info:
        DialogHandler.showFileInfo(getExplorer(), file);
        finishMode(mode);
        return true;

    case R.id.menu_multi_all_clear:
        getClipboard().clear();
        return true;

    case R.id.menu_context_share:

        // TODO: WTF is this?
        Intent mail = new Intent();
        mail.setType("application/mail");

        mail.setAction(android.content.Intent.ACTION_SEND);
        mail.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
        startActivity(mail);

        //mode.finish();
        return true;

    //         this is for bluetooth
    //         files.add(path);
    //         getHandler().sendFile(files);
    //         mode.finish();
    //         return true;
    }
    return false;
}

From source file:github.popeen.dsub.service.DownloadService.java

public static void startService(Context context, Intent intent) {
    PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
    if (Build.VERSION.SDK_INT < 26
            || (powerManager != null && powerManager.isIgnoringBatteryOptimizations(intent.getPackage()))) {
        context.startService(intent);/*from  w  ww  . ja  va2s  . c  om*/
    } else {
        context.startForegroundService(intent);
    }
}

From source file:org.wso2.iot.system.service.SystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    String AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();/*ww w .  j a  v  a  2s .  c o  m*/
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "IoT agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = !Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                || Preference.getBoolean(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:org.wso2.emm.system.service.EMMSystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();/*ww  w. j a va 2s.co m*/
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "EMM agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = (Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                && Preference.getBoolean(context,
                                        context.getResources()
                                                .getString(R.string.firmware_upgrade_automatic_retry)))
                                || !Preference.hasPreferenceKey(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private void showFileAttach() {
    final List<Intent> allIntents = new ArrayList<Intent>();

    // all openable...
    Intent contentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    contentIntent.setType(SafeSlingerConfig.MIMETYPE_ADD_ATTACH);
    contentIntent.addCategory(Intent.CATEGORY_OPENABLE);

    // camera/*from  w w w.  j  av  a2 s .c om*/
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    SafeSlinger.setTempCameraFileUri(SSUtil.makeCameraOutputUri());
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, SafeSlinger.getTempCameraFileUri());
    allIntents.add(cameraIntent);

    // audio recorder
    Intent recorderIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    recorderIntent.putExtra(MediaStore.EXTRA_OUTPUT, SSUtil.makeRecorderOutputUri());
    allIntents.add(recorderIntent);

    // our custom browser
    if (SSUtil.isExternalStorageReadable()) {
        Intent filePickIntent = new Intent(HomeActivity.this, FilePickerActivity.class);
        LabeledIntent fileIntent = new LabeledIntent(filePickIntent, filePickIntent.getPackage(),
                R.string.menu_FileManager, R.drawable.ic_menu_directory);
        allIntents.add(fileIntent);
    }

    // Chooser of file system options.
    Intent chooserIntent = Intent.createChooser(contentIntent, getString(R.string.title_ChooseFileLoad));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[] {}));
    startActivityForResult(chooserIntent, VIEW_FILEATTACH_ID);
}

From source file:com.android.launcher3.Launcher.java

private void startShortcutIntentSafely(Intent intent, Bundle optsBundle, ItemInfo info) {
    try {//from w  w w .ja  va  2s. c  o  m
        StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
        try {
            // Temporarily disable deathPenalty on all default checks. For eg, shortcuts
            // containing file Uri's would cause a crash as penaltyDeathOnFileUriExposure
            // is enabled by default on NYC.
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());

            if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
                String id = ((ShortcutInfo) info).getDeepShortcutId();
                String packageName = intent.getPackage();
                LauncherAppState.getInstance().getShortcutManager().startShortcut(packageName, id,
                        intent.getSourceBounds(), optsBundle, info.user);
            } else {
                // Could be launching some bookkeeping activity
                startActivity(intent, optsBundle);
            }
        } finally {
            StrictMode.setVmPolicy(oldPolicy);
        }
    } catch (SecurityException e) {
        // Due to legacy reasons, direct call shortcuts require Launchers to have the
        // corresponding permission. Show the appropriate permission prompt if that
        // is the case.
        if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction())
                && checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            setWaitingForResult(PendingRequestArgs.forIntent(REQUEST_PERMISSION_CALL_PHONE, intent, info));
            requestPermissions(new String[] { Manifest.permission.CALL_PHONE }, REQUEST_PERMISSION_CALL_PHONE);
        } else {
            // No idea why this was thrown.
            throw e;
        }
    }
}