如何检查是否意图可以从一些活动来处理?(How to check if an intent can

2019-07-21 14:57发布

我有这样的方法,到目前为止,但一出来就好像缺了点什么

比如我有一个返回false(如没有活动,可以处理这种类型的文件)的文件/sdcard/sound.3ga,但是当我从文件管理器打开它,它有没有问题,媒体播放器打开

我觉得这个意图是不完整的,我需要更多的东西,使我的自我确认handlerExists变量将只假,如果没有活动可以处理这个意图

PackageManager pm = getPackageManager();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uriString)).toString());
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent.setDataAndType(Uri.fromFile(new File(uriString)),mimetype);
boolean handlerExists = intent.resolveActivity(pm) != null;

Answer 1:

edwardxu的解决方案完全适用于我。

我只想澄清一点:

PackageManager packageManager = getActivity().getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent);
} else {
    Log.d(TAG, "No Intent available to handle action");
}


Answer 2:

PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
    //Then there is an Application(s) can handle your intent
} else {
    //No Application can handle your intent
}

你有没有试过这种意图是什么?

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(yourFileHere));


Answer 3:

if (intent.resolveActivity(getPackageManager()) == null) {
    // No Activity found that can handle this intent. 
}
else{
    // There is an activity which can handle this intent. 
}


Answer 4:

您可以使用:

public static boolean isAvailable(Context ctx, Intent intent) {
   final PackageManager mgr = ctx.getPackageManager();
   List<ResolveInfo> list =
      mgr.queryIntentActivities(intent, 
         PackageManager.MATCH_DEFAULT_ONLY);
   return list.size() > 0;
}


文章来源: How to check if an intent can be handled from some activity?