1

我是 Android 新手,我试图从包中检索活动列表,但出现错误。

我试过这段代码

Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager pm = this.getPackageManager();


PackageInfo info = pm.getPackageArchiveInfo(getPackageName(), PackageManager.GET_ACTIVITIES);

for (android.content.pm.ActivityInfo a : info.activities) {
    Log.i("ActivityInfo", a.name); 
}

但我得到一个空指针异常

10-02 02:17:12.168: E/AndroidRuntime(367): FATAL EXCEPTION: main
10-02 02:17:12.168: E/AndroidRuntime(367): java.lang.NullPointerException
10-02 02:17:12.168: E/AndroidRuntime(367):  at nyp.android.project.AnalyzeActivity.getActivityList(AnalyzeActivity.java:75)
10-02 02:17:12.168: E/AndroidRuntime(367):  at nyp.android.project.AnalyzeActivity.access$0(AnalyzeActivity.java:59)
10-02 02:17:12.168: E/AndroidRuntime(367):  at nyp.android.project.AnalyzeActivity$1.onClick(AnalyzeActivity.java:48)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.view.View.performClick(View.java:2408)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.view.View$PerformClick.run(View.java:8816)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.os.Handler.handleCallback(Handler.java:587)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.os.Looper.loop(Looper.java:123)
10-02 02:17:12.168: E/AndroidRuntime(367):  at android.app.ActivityThread.main(ActivityThread.java:4627)
10-02 02:17:12.168: E/AndroidRuntime(367):  at java.lang.reflect.Method.invokeNative(Native Method)
10-02 02:17:12.168: E/AndroidRuntime(367):  at java.lang.reflect.Method.invoke(Method.java:521)
10-02 02:17:12.168: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-02 02:17:12.168: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-02 02:17:12.168: E/AndroidRuntime(367):  at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

使用: getPackageInfo_getPackageArchiveInfo

try {
    PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);

    for (ActivityInfo activityInfo : packageInfo.activities) {
        Log.i("ActivityInfo", activityInfo.name);
    }
} catch (PackageManager.NameNotFoundException e) {
    // handle exception
}
于 2021-04-01T16:42:13.690 回答