我系统中的一个应用程序可以处理“ weibo:// abc”之类的URI,我想使用此URI启动意图。但是在其他机器上启动此URI之前,我需要检查此URI是否可以正确处理(没有较大延迟),我应该怎么办?

最佳答案

您可以使用PackageManager.queryIntentActivities()获取可以处理此Intent的“活动”列表。

以下代码检查意图是否可以得到处理。它是从android开发人员“ Can I Use This Intent?”文章中借用的。

/**
 * Indicates whether the specified action can be used as an intent. This
 * method queries the package manager for installed packages that can
 * respond to an intent with the specified action. If no suitable package is
 * found, this method returns false.
 *
 * @param context The application's environment.
 * @param action The Intent action to check for availability.
 *
 * @return True if an Intent with the specified action can be sent and
 *         responded to, false otherwise.
 */
public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}


像这样使用它:

if (isIntentAvailable(MyActivity.this,"weibo://abc"){
   //safe to startActivity here
} else {
   //no receiver for this activity
}

07-24 09:49
查看更多