Custom intent-chooser - why on Android 6 does it show empty cells?

瘦欲@ 提交于 2019-12-01 01:53:06
空気嫁

I spend some time to read ChooserActivity and ResolverActivity and kind of solving thoese problems.

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, 0);

    if (resolveInfos != null && !resolveInfos.isEmpty()) {
        List<Intent> targetIntents = new ArrayList<>();
        for (ResolveInfo resolveInfo : resolveInfos) {
            ActivityInfo activityInfo = resolveInfo.activityInfo;
            // remove activities which packageName contains 'ttt' for example
            if (activityInfo.packageName.contains("ttt")) {
                continue;
            }
            Intent targetIntent = new Intent(Intent.ACTION_SEND);
            targetIntent.setType("text/plain");
            targetIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.setting_share_app_subject));
            targetIntent.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.setting_share_app_body));
            targetIntent.setPackage(activityInfo.packageName);
            targetIntent.setComponent(new ComponentName(activityInfo.packageName, activityInfo.name));

            // wrap with LabeledIntent to show correct name and icon

            LabeledIntent labeledIntent = new LabeledIntent(targetIntent, activityInfo.packageName, resolveInfo.labelRes, resolveInfo.icon);

            // add filtered intent to a list
            targetIntents.add(labeledIntent);
        }
        Intent chooserIntent;
        // deal with M list seperate problem
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // create chooser with empty intent in M could fix the empty cells problem
            chooserIntent = Intent.createChooser(new Intent(), context.getString(R.string.setting_share_app_title));
        } else {
            // create chooser with one target intent below M
            chooserIntent = Intent.createChooser(targetIntents.remove(0), context.getString(R.string.setting_share_app_title));
        }
        if (chooserIntent == null) {
            return;
        }
        // add initial intents
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[targetIntents.size()]));
        try {
            context.startActivity(chooserIntent);
        } catch (ActivityNotFoundException e) {
            Logger.e(TAG, e, e);
        }
    }

EDIT: seems on Android Q (10 - API 29) this is broken, and will show just up to 2 items instead of all of them. Asked about this again here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!