android 5.0 , 已经不能按此方式获取包名:
ComponentName localComponentName = ((ActivityManager.RunningTaskInfo) ((ActivityManager) getSystemService("activity")).getRunningTasks(1).get(0)).topActivity;
String nowPkgName = localComponentName.getPackageName();
经过查找资料,发现有新的方法获取:
public static String getCurrentPkgName(Context context) {
RunningAppProcessInfo currentInfo = null;
Field field = null;
int START_TASK_TO_FRONT = 2;
String pkgName = null;
try {
field = RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception e) { e.printStackTrace(); }
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (RunningAppProcessInfo app : appList) {
if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Integer state = null;
try {
state = field.getInt( app );
} catch (Exception e) { e.printStackTrace(); }
if (state != null && state == START_TASK_TO_FRONT) {
currentInfo = app;
break;
}
}
}
if (currentInfo != null) {
pkgName = currentInfo.processName;
}
return pkgName;
}
获取的是进程名, 一般就是 app 包名,如果是自定义进程的,则要另外区分.