How to check if an intent can be handled from some

2019-01-04 09:24发布

I have this method so far , but it came up like something is missing

for example I have a file /sdcard/sound.3ga that returns false ( like there is no activity that can handle this type of file ) , But when I open it from the file manager it opens with the media player with no problem

I think this intent is not complete and I need to to something more to make my self sure that the handlerExists variable will be false ONLY if there is no activity that can handle this intent

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;

4条回答
Evening l夕情丶
2楼-- · 2019-01-04 09:36

edwardxu's solution works perfectly for me.

Just to clarify a bit:

PackageManager packageManager = getActivity().getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent);
} else {
    Log.d(TAG, "No Intent available to handle action");
}
查看更多
Root(大扎)
3楼-- · 2019-01-04 09:49
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
}

Have you tried this intent?

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(yourFileHere));
查看更多
太酷不给撩
4楼-- · 2019-01-04 09:52

You can use:

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;
}
查看更多
相关推荐>>
5楼-- · 2019-01-04 09:54
if (intent.resolveActivity(getPackageManager()) == null) {
    // No Activity found that can handle this intent. 
}
else{
    // There is an activity which can handle this intent. 
}
查看更多
登录 后发表回答