LoginSignup
22
20

More than 5 years have passed since last update.

Intentで開くアプリ一覧の中に自分自身が出ないようにする

Posted at

Androidでは暗黙的Intentを用いることで「◯◯な動作をするActivity」の一覧をダイアログとしてユーザに提示することが出来ます。

これは便利な機能なのですが、Emaki のように画像を外部から保存することも外部にエクスポートすることも出来るようなアプリの場合、Emaki上の画像を外部アプリにエクスポートしようとすると、アプリ選択のダイアログにEmaki自身が出てきてちょっと煩わしいです。

以下のようにPackageManagerを利用して、自分自身に対応するIntentをはじいてあげることで、これを回避出来ます。

    public static Intent createChooserWithoutMe(Context context, Intent target, CharSequence title) {
        List<ResolveInfo> resolveInfoList
                = context.getPackageManager().queryIntentActivities(target, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfoList.isEmpty()) {
            return Intent.createChooser(target, title);
        }

        Collections.sort(resolveInfoList, new ResolveInfo.DisplayNameComparator(context.getPackageManager()));
        List<Intent> targetIntents = new ArrayList<Intent>();
        for (ResolveInfo resolveInfo : resolveInfoList) {
            if (context.getApplicationContext().getPackageName().equals(resolveInfo.activityInfo.packageName)) {
                continue;
            }
            Intent intent = new Intent(target);
            intent.setPackage(resolveInfo.activityInfo.packageName);
            intent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
            targetIntents.add(intent);
        }

        Intent chooserIntent = Intent.createChooser(targetIntents.remove(0), title);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[]{}));
        return chooserIntent;
    }
22
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20