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;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public static boolean isIntentAvailable(
Context context, String action)
{
    final PackageManager packageManager =     
        context.getPackageManager();
    final Intent i = new Intent(action);
    List list =
        packageManager.queryIntentActivities(i,
        PackageManager.MATCH_DEFAULT_ONLY);
    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);
    startActivity(Intent.createChooser(
        i, "List of Apps"));
} else {
    Toast.makeText(this, "Intent is not available",
    Toast.LENGTH_LONG).show();
}

No comments: