Mehdi Akin
Mehdi Akin

Reputation: 11

NullPointerException when use getLaunchIntentForPackage

I'm trying to start a third party app(here is Launcher) by using this code:

  Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
            String currentHomePackage = resolveInfo.activityInfo.packageName;
            openApp(getApplicationContext(),currentHomePackage);

openApp:

public static boolean openApp(Context context, String packageName) {
    PackageManager manager = context.getPackageManager();
    try {
        Intent i = manager.getLaunchIntentForPackage(packageName);
        if (i == null) {

            return false;
            //throw new PackageManager.NameNotFoundException();
        }
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
        return true;
    } catch (Exception e) {

        return false;
    }
}

but I get a NullPointerException! This code gets my launcher package name correctly, but I can't open it! Help me please and don't get me negative points!

logcat:

07-30 18:59:47.206  16079-16079/ir.whiteapp.keepme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at ir.whiteapp.keepme.AlertBox.openApp(AlertBox.java:80)
        at ir.whiteapp.keepme.AlertBox$1.onClick(AlertBox.java:52)
        at android.view.View.performClick(View.java:4204)
        at android.view.View$PerformClick.run(View.java:17355)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

Upvotes: 0

Views: 1092

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006614

There is no requirement that getLaunchIntentForPackage() return anything. Quoting the documentation:

Returns: A fully-qualified Intent that can be used to launch the main activity in the package. Returns null if the package does not contain such an activity, or if packageName is not recognized.

In particular, a home screen implementation does not need a launch Intent (ACTION_MAIN/CATEGORY_LAUNCHER), as normally it is not launched by other home screen implementations.

Upvotes: 1

Related Questions