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:cc.flydev.launcher.InstallShortcutReceiver.java

public static void removeFromInstallQueue(SharedPreferences sharedPrefs, ArrayList<String> packageNames) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG) {
            Log.d(TAG, "APPS_PENDING_INSTALL: " + strings + ", removing packages: " + packageNames);
        }//from   w  w  w  .j a  v a2 s.c o m
        if (strings != null) {
            Set<String> newStrings = new HashSet<String>(strings);
            Iterator<String> newStringsIter = newStrings.iterator();
            while (newStringsIter.hasNext()) {
                String json = newStringsIter.next();
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                    String pn = launchIntent.getPackage();
                    if (pn == null) {
                        pn = launchIntent.getComponent().getPackageName();
                    }
                    if (packageNames.contains(pn)) {
                        newStringsIter.remove();
                    }
                } catch (org.json.JSONException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                } catch (java.net.URISyntaxException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                }
            }
            sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>(newStrings)).commit();
        }
    }
}

From source file:com.android.launcher4.InstallShortcutReceiver.java

public static void removeFromInstallQueue(SharedPreferences sharedPrefs, ArrayList<String> packageNames) {
    if (packageNames.isEmpty()) {
        return;/*from www.jav  a  2s .  c o  m*/
    }
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG) {
            Log.d(TAG, "APPS_PENDING_INSTALL: " + strings + ", removing packages: " + packageNames);
        }
        if (strings != null) {
            Set<String> newStrings = new HashSet<String>(strings);
            Iterator<String> newStringsIter = newStrings.iterator();
            while (newStringsIter.hasNext()) {
                String json = newStringsIter.next();
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                    String pn = launchIntent.getPackage();
                    if (pn == null) {
                        pn = launchIntent.getComponent().getPackageName();
                    }
                    if (packageNames.contains(pn)) {
                        newStringsIter.remove();
                    }
                } catch (org.json.JSONException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                } catch (java.net.URISyntaxException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                }
            }
            sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>(newStrings)).commit();
        }
    }
}

From source file:com.android.launcher4.InstallShortcutReceiver.java

static void flushInstallQueue(Context context) {
    String spKey = LauncherAppState.getSharedPreferencesKey();
    SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
    ArrayList<PendingInstallShortcutInfo> installQueue = getAndClearInstallQueue(sp);
    if (!installQueue.isEmpty()) {
        Iterator<PendingInstallShortcutInfo> iter = installQueue.iterator();
        ArrayList<ItemInfo> addShortcuts = new ArrayList<ItemInfo>();
        int result = INSTALL_SHORTCUT_SUCCESSFUL;
        String duplicateName = "";
        while (iter.hasNext()) {
            final PendingInstallShortcutInfo pendingInfo = iter.next();
            //final Intent data = pendingInfo.data;
            final Intent intent = pendingInfo.launchIntent;
            final String name = pendingInfo.name;

            if (LauncherAppState.isDisableAllApps() && !isValidShortcutLaunchIntent(intent)) {
                if (DBG)
                    Log.d(TAG, "Ignoring shortcut with launchIntent:" + intent);
                continue;
            }//  w  w w.  j  av  a2s .  co  m

            final boolean exists = LauncherModel.shortcutExists(context, name, intent);
            //final boolean allowDuplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);

            // If the intent specifies a package, make sure the package exists
            String packageName = intent.getPackage();
            if (packageName == null) {
                packageName = intent.getComponent() == null ? null : intent.getComponent().getPackageName();
            }
            if (packageName != null && !packageName.isEmpty()) {
                UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
                if (!LauncherModel.isValidPackage(context, packageName, myUserHandle)) {
                    if (DBG)
                        Log.d(TAG, "Ignoring shortcut for absent package:" + intent);
                    continue;
                }
            }

            if (!exists) {
                // Generate a shortcut info to add into the model
                ShortcutInfo info = getShortcutInfo(context, pendingInfo.data, pendingInfo.launchIntent);
                addShortcuts.add(info);
            }

        }

        // Notify the user once if we weren't able to place any duplicates
        if (result == INSTALL_SHORTCUT_IS_DUPLICATE) {
            Toast.makeText(context, context.getString(R.string.shortcut_duplicate, duplicateName),
                    Toast.LENGTH_SHORT).show();
        }

        // Add the new apps to the model and bind them
        if (!addShortcuts.isEmpty()) {
            LauncherAppState app = LauncherAppState.getInstance();
            app.getModel().addAndBindAddedWorkspaceApps(context, addShortcuts);
        }
    }
}

From source file:de.baumann.hhsmoodle.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView) {

    webView.setWebViewClient(new WebViewClient() {

        ProgressDialog progressDialog;/*from   w  w  w  .  ja  v a 2 s  . c o m*/
        int numb;

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            ViewPager viewPager = (ViewPager) from.findViewById(R.id.viewpager);
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(from);
            sharedPref.edit().putString("loadURL", webView.getUrl()).apply();

            if (viewPager.getCurrentItem() == 0) {
                if (url != null) {
                    from.setTitle(webView.getTitle());
                }
            }

            if (url != null && url.contains("moodle.huebsch.ka.schule-bw.de/moodle/")
                    && url.contains("/login/")) {

                if (viewPager.getCurrentItem() == 0 && numb != 1) {
                    progressDialog = new ProgressDialog(from);
                    progressDialog.setTitle(from.getString(R.string.login_title));
                    progressDialog.setMessage(from.getString(R.string.login_text));
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                            from.getString(R.string.toast_settings), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    helper_main.switchToActivity(from, Activity_settings.class, true);
                                }
                            });
                    progressDialog.show();
                    numb = 1;
                    progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            numb = 0;
                        }
                    });
                }

            } else if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.cancel();
                numb = 0;
            }

            swipeRefreshLayout.setRefreshing(false);

            class_SecurePreferences sharedPrefSec = new class_SecurePreferences(from, "sharedPrefSec",
                    "Ywn-YM.XK$b:/:&CsL8;=L,y4", true);
            String username = sharedPrefSec.getString("username");
            String password = sharedPrefSec.getString("password");

            final String js = "javascript:" + "document.getElementById('password').value = '" + password + "';"
                    + "document.getElementById('username').value = '" + username + "';"
                    + "var ans = document.getElementsByName('answer');"
                    + "document.getElementById('loginbtn').click()";

            if (Build.VERSION.SDK_INT >= 19) {
                view.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
            } else {
                view.loadUrl(js);
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return handleUri(uri);
        }

        private boolean handleUri(final Uri uri) {
            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }
    });
}

From source file:de.baumann.browser.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView, final EditText editText) {

    webView.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swipeRefreshLayout.setRefreshing(false);
            editText.setText(webView.getTitle());
            if (webView.getTitle() != null && !webView.getTitle().equals("about:blank")) {
                try {
                    final Database_History db = new Database_History(from);
                    db.addBookmark(webView.getTitle(), webView.getUrl());
                    db.close();//from  w  w w. j  a v  a  2 s . c  o m
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return handleUri(uri);
        }

        private boolean handleUri(final Uri uri) {

            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }

    });
}

From source file:com.tenmiles.helpstack.service.AttachmentDownloadReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    String package_name = intent.getPackage();
    String cpackage = context.getPackageName();

    if (package_name.equals(cpackage) && DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
        downloadCompleted(context, intent);
    } else if (package_name.equals(cpackage) && DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
        notificationClicked(context, intent);
    }/*from  ww  w.  j a  v a  2  s. c  o  m*/
}

From source file:com.android.settings.security.SecurityFeatureProviderImpl.java

@VisibleForTesting
void updatePreferencesToRunOnWorkerThread(Context context, PreferenceScreen preferenceScreen,
        DashboardCategory dashboardCategory) {

    int tilesCount = (dashboardCategory != null) ? dashboardCategory.getTilesCount() : 0;
    Map<String, IContentProvider> providerMap = new ArrayMap<>();
    for (int i = 0; i < tilesCount; i++) {
        Tile tile = dashboardCategory.getTile(i);
        // If the tile does not have a key or appropriate meta data, skip it.
        if (TextUtils.isEmpty(tile.key) || (tile.metaData == null)) {
            continue;
        }/*from  w  ww . j  av a 2 s  . c  om*/
        Preference matchingPref = preferenceScreen.findPreference(tile.key);
        // If the tile does not have a matching preference, skip it.
        if (matchingPref == null) {
            continue;
        }
        // Check if the tile has content providers for dynamically updatable content.
        final String iconUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_ICON_URI, null);
        final String summaryUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_SUMMARY_URI, null);
        if (!TextUtils.isEmpty(iconUri)) {
            String packageName = null;
            if (tile.intent != null) {
                Intent intent = tile.intent;
                if (!TextUtils.isEmpty(intent.getPackage())) {
                    packageName = intent.getPackage();
                } else if (intent.getComponent() != null) {
                    packageName = intent.getComponent().getPackageName();
                }
            }
            Pair<String, Integer> icon = TileUtils.getIconFromUri(context, packageName, iconUri, providerMap);
            if (icon != null) {
                sIconCache.put(iconUri, icon);
                // Icon is only returned if the icon belongs to Settings or the target app.
                // setIcon must be called on the UI thread.
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            matchingPref.setIcon(context.getPackageManager()
                                    .getResourcesForApplication(icon.first /* package name */)
                                    .getDrawable(icon.second /* res id */, context.getTheme()));
                        } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                            // Intentionally ignored. If icon resources cannot be found, do not
                            // update.
                        }
                    }
                });
            }
        }
        if (!TextUtils.isEmpty(summaryUri)) {
            String summary = TileUtils.getTextFromUri(context, summaryUri, providerMap,
                    TileUtils.META_DATA_PREFERENCE_SUMMARY);
            sSummaryCache.put(summaryUri, summary);
            // setSummary must be called on UI thread.
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Only update the summary if it has actually changed.
                    if (summary == null) {
                        if (matchingPref.getSummary() != null) {
                            matchingPref.setSummary(summary);
                        }
                    } else if (!summary.equals(matchingPref.getSummary())) {
                        matchingPref.setSummary(summary);
                    }
                }
            });
        }
    }
}

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

@Override
public void onReceive(Context context, Intent intent) {
    String packg = intent.getPackage();
    if (TextUtils.isEmpty(packg) || !packg.equals(context.getPackageName().toString())) {
        return;//from   ww w  .j av a  2 s.c o  m
    }
    if (ACTION_PUSH.equals(intent.getAction())) {
        if (intent.hasExtra(PushReportConstants.PUSH_DATA_INFO_KEY)) {
            newPushNotification(context, intent);
        } else {
            oldPushNotification(context, intent);
        }
    }
}

From source file:nirwan.cordova.plugin.printer.Printer.java

private void adjustSettingsForPrintController(Intent intent, String mimeType) {
    if (mimeType == null) {
        mimeType = "image/png";
    }/*from   ww  w  .  j  a v  a 2s  .  co m*/
    String appId = intent.getPackage();

    // Check for special cases that can receive HTML
    //if (appId.equals("com.rcreations.send2printer") || appId.equals("com.dynamixsoftware.printershare")) {
    //  mimeType = "text/html";
    intent.setType(mimeType);
    //}

    //   intent.setType(mimeType);
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * Sends plugin info back to Vanilla Music service.
 * @param intent intent from player/*from  w w  w  . j  a va2s  .  c o  m*/
 */
private void handleRequestPluginParams(Intent intent) {
    Intent answer = new Intent(ACTION_HANDLE_PLUGIN_PARAMS);
    answer.setPackage(intent.getPackage());
    answer.putExtra(EXTRA_PARAM_PLUGIN_NAME, getString(R.string.tag_editor));
    answer.putExtra(EXTRA_PARAM_PLUGIN_APP, getApplicationInfo());
    answer.putExtra(EXTRA_PARAM_PLUGIN_DESC, getString(R.string.plugin_desc));
    sendBroadcast(answer);
}