/** * 獲取程式包名(本程式包名5.0版本上下都可獲取) * * @return */ public String getTaskPackname() { ActivityManager.RunningAppProcessInfo currentInfo = null; Field field ...
- /**
- * 獲取程式包名(本程式包名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;
- }