Android judges whether any app is running in the foreground

Determine whether the application is in the foreground

Generally, we judge whether an application is in the foreground through the ActivityManager interface.
Next, we encapsulate it into a function to ensure the lowest coupling and easy to use

//只需要获取当前的上下文,即可判断应用是否在前台
public static boolean isAppRunning(Context context) {
    
    
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(1);
        if(list.size() <= 0) {
    
    
            return false;
        }
        Slog.i("log","classname is "+list.get(0).topActivity.getClassName());
        if( list.get(0).topActivity.getClassName().equals("需要比较的activity的包名") ) {
    
    
            return true;
        } else {
    
    
            return false;
        }
}

Guess you like

Origin blog.csdn.net/fancynthia/article/details/123441055
Recommended