如何从ACTION_VIEW Intent中排除特定的应用程序?

时间:2013-09-08 10:50:20

标签: android android-intent

我正在尝试在浏览器中加载推特网址。

在我的手机中,我已经安装了Twitter应用程序。我正在尝试使用ACTION_VIEW意图打开网址。但是,当我调用intent时,android会显示默认的选择器对话框,其中也包含twitter应用程序(如果它安装在设备上)。我想只使用浏览器打开URL。 我想从对话框中排除Twitter应用程序。我希望设备中的所有可用浏览器都显示在对话框中,而不是像twitter,facebook等本机应用程序。

有可能吗?如果可能的话,任何人都可以帮助我实现它。为了清楚起见,我还附上了我的代码和截图以及这个问题。

String url = "https://twitter.com";
MimeTypeMap map = MimeTypeMap.getSingleton();
String type = map.getMimeTypeFromExtension(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setType(type);
i.setData(Uri.parse(url));
startActivity(i);

enter image description here

2 个答案:

答案 0 :(得分:14)

我需要做类似的事情,并发现this回答有帮助。我修改了它,这是一个完整的解决方案:

public static void openFileWithInstalledAppExceptCurrentApp(File file, final Activity activity) {
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String ext = file.getName().substring(file.getName().indexOf(".")+1);
    String type = mime.getMimeTypeFromExtension(ext);
    intent.setDataAndType(Uri.fromFile(file),type);
    PackageManager packageManager = activity.getPackageManager();
    List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
    String packageNameToHide = "com.test.app";
    ArrayList<Intent> targetIntents = new ArrayList<Intent>();
    for (ResolveInfo currentInfo : activities) {
            String packageName = currentInfo.activityInfo.packageName;
        if (!packageNameToHide.equals(packageName)) {
            Intent targetIntent = new Intent(android.content.Intent.ACTION_VIEW);
            targetIntent.setDataAndType(Uri.fromFile(file),type);
            targetIntent.setPackage(packageName);
            targetIntents.add(targetIntent);
        }
    }
    if(targetIntents.size() > 0) {
        Intent chooserIntent = Intent.createChooser(targetIntents.remove(0), "Open file with");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[] {}));
        activity.startActivity(chooserIntent);
    }
    else {
        Toast.makeText(this, "No app found", Toast.LENGTH_SHORT).show();
    }
}

答案 1 :(得分:3)

您只需将目标包设置为意图:

String url = "https://twitter.com";
MimeTypeMap map = MimeTypeMap.getSingleton();
String type = map.getMimeTypeFromExtension(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setType(type);
i.setData(Uri.parse(url));
ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

但是,如果他们安装了一些自定义浏览器并希望将其用作默认浏览器,则会对用户造成干扰。

您可以尝试使用以下方法检测默认浏览器:

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://example.com"));
List<ResolveInfo> list = context.getPackageManager()
    .queryIntentActivities(i, 0);
// walk through list and select your most favorite browser
相关问题