Saturday, March 29, 2014

Android Tip - Launch Application by Package Name

One common way to launch an application is through its activity. However, what happens if you do not know the name of the activity?  So how do you launch an intent to launch the application?
In this case, you need to launch the application directly using its package name.

The following appIsInstalled() method checks if a package is already installed on the target device:

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

private boolean appIsInstalled(String packageName) {
    PackageManager pm = getPackageManager();
    boolean appInstalled = false;
    try {
        appInstalled = true;
    } catch (PackageManager.NameNotFoundException e) {
        appInstalled = false;
    return appInstalled;               

To launch a package directly using its package name, you can use the getLaunchIntentForPackage() of the PackageManager class to create an intent for the app:

        String packageName =
        if (appIsInstalled(packageName)) {
            Intent i = getPackageManager().
        } else {
                "App not installed on the device.",

Then, you launch the intent as usual using the startActivity() method.

No comments: