我是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);
}
但是我得到了一个nullpointerexception
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)
答案 0 :(得分: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
}