- /**
- * 获取程序包名(本程序包名5.0版本上下都可获取)
- *
- * @return
- */
- public String getTaskPackname() {
- ActivityManager.RunningAppProcessInfo currentInfo = null;
- Field field = null;
- int START_TASK_TO_FRONT = 2;
- String currentApp = "CurrentNULL";
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
- try {
- field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
- } catch (Exception e) {
- e.printStackTrace();
- }
- ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
- List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
- for (ActivityManager.RunningAppProcessInfo app : appList) {
- if (app.importance == ActivityManager.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) {
- currentApp = currentInfo.processName;
- }
- } else {
- ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
- List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
- currentApp = tasks.get(0).processName;
- }
- Log.e("TAG", "Current App in foreground is: " + currentApp);
- return currentApp;
- }
转载于:https://www.cnblogs.com/gholl/p/5993211.html