判断当前 App 是否被切换到后台的方法

有两种方法:

1. 需要权限  <uses-permission android:name="android.permission.GET_TASKS"/>, 普通App也可获取,不需要确认,Android 5.1 之后已经废弃,但是 compileSdkVersion 设为 28 还可以使用,方法如下:

public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

2. 不需要权限:

public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    Log.i("后台", appProcess.processName);
                    return true;
                }else{
                    Log.i("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

其他,获取当前 App 进程名字:

public static String getCurrentProcessName(Context context) {
        try {
            int myid = Process.myPid();
            ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
            Iterator iter = appProcesses.iterator();

            while(iter.hasNext()) {
                ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)iter.next();
                if (info.pid == myid) {
                    return info.processName;
                }
            }
        } catch (Exception e) {
            
        }

        return null;
    }

 

展开阅读全文

没有更多推荐了,返回首页