Android 获取当前 运行 应用程序包名称

Android get current running application package name

我有以下代码 运行 在 Android 5.0 和 6.0 中正确,但如果我将此应用程序用于 Android 4.4 设备,则应用程序会崩溃。请帮我解决这个问题。 下面是我的代码

 if (Build.VERSION.SDK_INT > 20) {
     packageName = mActivityManager.getRunningAppProcesses().get(1).processName;
 } else { 
     packageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
 }
 Log.e("Package : ", "" + packageName);

显示错误,

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.keyboardsample, PID: 23694 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SEND typ=image/png flg=0x1 pkg=com.keyboardsample (has clip) (has extras) } at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1632) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424) at android.app.Activity.startActivityForResult(Activity.java:3424) at android.app.Activity.startActivityForResult(Activity.java:3385) at android.app.Activity.startActivity(Activity.java:3627) at android.app.Activity.startActivity(Activity.java:3595) at com.keyboardsample.PhotoActivity.onItemClick(PhotoActivity.java:80) at android.widget.AdapterView.performItemClick(AdapterView.java:299) at android.widget.AbsListView.performItemClick(AbsListView.java:1113) at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911) at android.widget.AbsListView.run(AbsListView.java:3645) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method)

您可以使用

getApplicationContext().getPackageName();