Thursday, August 15, 2013

Android Tip: Checking the Availability of an Intent

Android developers are all too familiar with the concepts of Intent. But often, if you are not careful, calling an Intent using an action name that matches no activities will result in your application crashing.  In order to prevent that, you are advised to check for the availability of that Intent prior to calling it.

To check if an Intent is available, use the isIntentAvailable() method, defined below:

import android.content.Context;

public static boolean isIntentAvailable(
Context context, String action)
    final PackageManager packageManager =     
    final Intent i = new Intent(action);
    List list =
    return list.size() > 0;

This method returns a true if there is at least one activity that matches your action name. You can call it as follows:

String action = "net.learn2develop.secondactivity";

//---check if intent is available---
if (isIntentAvailable(this, action)) {
    Intent i = new Intent(action);
        i, "List of Apps"));
} else {
    Toast.makeText(this, "Intent is not available",

No comments: