Intent.EXTRA_INITIAL_INTENTS不会在选择器中添加应用程序

时间:2016-01-21 13:21:42

标签: android android-intent

我正在尝试从我的应用分享一些数据。我必须发送电子邮件和不同文本的不同文本,以防用户选择其他应用程序。

                Intent emailIntent = new Intent(Intent.ACTION_SEND);
                emailIntent.setType("ye");
                PackageManager pm = getPackageManager();
                Intent sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("text/plain");


                Intent openInChooser = Intent.createChooser(emailIntent, "Share via");



                List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
                List<LabeledIntent> intentList = new ArrayList<>();

                for(int i=0;i<resInfo.size();i++)
                {
                    ResolveInfo ri = resInfo.get(i);
                    String packageName = ri.activityInfo.packageName;
                    Log.d("package", i + " " + packageName);
                    if(packageName.contains("android.email")){
                        emailIntent.setPackage(packageName);
                        emailIntent.putExtra(Intent.EXTRA_TEXT, "This is email");
                    }
                    else
                    {
                        Intent intent = new Intent();

                        intent.setComponent(new ComponentName(packageName,ri.activityInfo.packageName));
                        intent.setAction(Intent.ACTION_SEND);
                        intent.setType("text/plain");
                        intent.putExtra(Intent.EXTRA_TEXT, "Sharing via other app");
                        intent.setPackage(packageName);
                        intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
                    }
                }


                LabeledIntent [] extraIntents  = new LabeledIntent[intentList.size()];
                extraIntents = intentList.toArray(extraIntents);

                openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
                startActivity(openInChooser);

我在setType中的原始意图中给出了一个随机字符串,以便它只显示所选的应用程序。但是,当我点击共享时,会出现一个空窗口。 我已经检查过调试器,我的extraIntents包含24个意图。在startActivity之后,我选择的选项中没有任何内容。

1 个答案:

答案 0 :(得分:5)

在您的情况下,emailIntent会因为您设置的随机类型而返回0个应用。在

Intent openInChooser = Intent.createChooser(emailIntent, "Share via");

如果你传递的意图返回0个应用程序,那么它会忽略EXTRA_INITIAL_INTENTS标志。

可能的解决方案,

            ......
            extraIntents = intentList.toArray(extraIntents);
            Intent firstIntent = extraIntents.remove(0); // assuming you will have at least one Intent
            Intent openInChooser = Intent.createChooser(firstIntent, "Share via");

            openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
            startActivity(openInChooser);