How to check if an intent can be handled from some activity?
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");
}
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));
if (intent.resolveActivity(getPackageManager()) == null) {
// No Activity found that can handle this intent.
}
else{
// There is an activity which can handle this intent.
}
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;
}
Using Kotlin If you need to do something when intent is not available,
fun isIntentAvailable(context: Context, action: String?): Boolean {
val packageManager = context.packageManager
val intent = Intent(action)
val resolveInfo: List<*> = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return resolveInfo.isNotEmpty()
}
Implement this method as
private const val SAMPLE_INTENT = "com.realwear.barcodereader.intent.action.SCAN_BARCODE"
if(isIntentAvailable(this,SAMPLE_INTENT)){
//Do Stuff
}
If you don't have anything to do,
Intent(SAMPLE_INTENT).also { barcodeReaderIntent ->
barcodeReaderIntent.resolveActivity(packageManager)?.also {
barcodeReaderIntent.putExtra(EXTRA_CODE_128, false)
startActivityForResult(barcodeReaderIntent, BARCODE_REQUEST_CODE)
}
}