使用getLaunchIntentForPackage时出现NullPointerException

时间:2015-07-30 14:02:14

标签: java android

我正在尝试使用此代码启动第三方应用(此处为Launcher):

  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;
    }
}

但我得到NullPointerException!此代码正确获取我的启动程序包名称,但我无法打开它!请帮助我,不要给我负面的点数!

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)

1 个答案:

答案 0 :(得分:1)

不要求getLaunchIntentForPackage()返回任何内容。引用the documentation

  

返回:一个完全限定的Intent,可用于启动包中的主要活动。如果包不包含此类活动,或者无法识别packageName,则返回null。

特别是,主屏幕实现不需要启动IntentACTION_MAIN / CATEGORY_LAUNCHER),因为通常它不会被其他主屏幕实现启动。