Tuesday, February 18, 2014

Loading app/web page from Android intent when app is disabled

In Android, it's pretty easy to load a page from Facebook or Twitter or a similar one, from our very own app. By passing an intent with the request, the related app will automatically show up with the desired content. If the app is not installed we can detect that scenario so that, for instance, the browser starts up and loads the link for the wanted page. With Google+  it's even simpler, as we just need to pass the web URL. Android then selects if it should use the Google+ app or a browser (taking into account users' preferences).

However, what if the app is installed but has been disabled (for example through App Quarantine)?

Let's consider Facebook as the app/website to load from our Android application.

Typical code for loading a page is something like the following:
Intent intent;
try {
    getPackageManager().getPackageInfo("com.facebook.katana", 0);
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/620681997952698"));
} catch (NameNotFoundException e) {
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/620681997952698"));
}
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(getApplicationContext(),
            getString(R.string.facebook_error), Toast.LENGTH_LONG).show();
}

Which works most of the time: with or without the app installed.

However, if the user has Facebook installed but disabled (for example by using App Quarantine), this method will not work. The intent for the Facebook app will be selected but it will not be able to process it as it is disabled, ultimately resulting in the Toast above.

So, a quick fix (and the whole point of this post) is to detect if the app has been disabled and then choose to use the web URL:

Instead of:
getPackageManager().getPackageInfo("com.facebook.katana", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/620681997952698"));

You can use the following to decide what to do:
PackageInfo info = getPackageManager().getPackageInfo("com.facebook.katana", 0);
if(info.applicationInfo.enabled)
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/620681997952698"));
else
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/620681997952698"));

This process is similar for other apps (not required for Google+).

Some links:

No comments:

Post a Comment

Feel free to share your thoughts!