如何以编程方式设置文件或 url "open with"?

How to set file or url "open with" programmatically?

当文件或url打开时,Android询问用户如何打开。我的应用程序需要设置此选项。如果没有解决方案,我无法完成申请。请告诉我该怎么做。

如果您与 Intent 共享文件,您可以先创建 Intent openWith 对象(但还不能 运行)。然后像这样列出所有可用的活动:

PackageManager pm = (Activity)this.getPackageManager();
List<ResolveInfo> resInfo = pm.queryIntentActivities(openWith, 0);
for (int i = 0; i < resInfo.size(); i++) {
    ResolveInfo ri = resInfo.get(i);
    String packageName = ri.activityInfo.packageName;
    String label = (String) ri.loadLabel(pm);
    String activity = ri.activityInfo.name;
    // choose needed packageName and activity here
}

然后将选定的 packageName 和 activity 对添加到 "open with" 操作的意图中:

intent.setComponent(new ComponentName(packageName, activity));

和运行它。

您想在您的应用中实现 files/urls 打开功能,对吧? 这是文档 https://developer.android.com/training/basics/intents/filters.html 所以你的 'viewer' activity 必须有这样的意图过滤器

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="*/*" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:scheme="http|https" />
</intent-filter>