How to check if an intent can be handled from some activity?

Lukap picture Lukap · Mar 14, 2013 · Viewed 61.3k times · Source

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;

Answer

Sparky1 picture Sparky1 · May 1, 2015

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");
}