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.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

private boolean appIsInstalled(String packageName) {
    PackageManager pm = getPackageManager();
    boolean appInstalled = false;
    try {
        pm.getPackageInfo(packageName,
            PackageManager.GET_ACTIVITIES);
        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 =
            "net.learn2develop.barcodescanner";
        
        if (appIsInstalled(packageName)) {
            Intent i = getPackageManager().
                getLaunchIntentForPackage(packageName);
            startActivity(i);
        } else {
            Toast.makeText(this,
                "App not installed on the device.",
                Toast.LENGTH_LONG).show();
        }


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

No comments: