Android判断应用在前台和切换应用到前台的方法

/**
 * 判断应用在前台
 */
public static boolean isForeground(Context context) {
    boolean isForeground = false;
    ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    if (activityManager != null) {
        ComponentName componentName = activityManager.getRunningTasks(1).get(0).topActivity;
        if (componentName != null) {
            isForeground = componentName.getPackageName().equals(context.getPackageName());
        }
    }
    if (isForeground) {
        isForeground = isForegroundByProcess();
    }
    return isForeground;
}

/**
 * 根据进程判断应用在前台
 */
private static boolean isForegroundByProcess() {
    boolean isForeground = true;
    String filePath = "/proc/" + android.os.Process.myPid() + "/cgroup";
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line = br.readLine();
        if (line != null && line.contains("bg_non_interactive")) {
            isForeground = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return isForeground;
}

/**
 * 切换应用到前台
 */
public static void switchToForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
    for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
        ComponentName componentName = taskInfo.topActivity;
        if (componentName != null && componentName.getPackageName().equals(context.getPackageName())) {
            activityManager.moveTaskToFront(taskInfo.id, 0);
            break;
        }
    }
}

参考资料:

判断App位于前台或者后台的6种方法

Android 将后台应用切换到前台

发表评论