您的位置:首页 > 其它

判断程序是否在后台运行工具

2018-03-27 11:47 351 查看
public class AppUtils {
    /**
     * 判断应用是否在后台
     */
    public static boolean isBackgroundRunning() {
        try {
            Context context = BaseApp.getInstance();
            if(context == null) return false; // 防止应用打开时没来得及初始化AppContext
            String processName = context.getPackageName();

            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

            if (activityManager == null) return true;
            // get running application processes
            List<ActivityManager.RunningAppProcessInfo> processList = activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo process : processList) {
                if (process.processName.startsWith(processName)) {
                    boolean isBackground = process.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                            && process.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
                    boolean isLockedState = keyguardManager.inKeyguardRestrictedInputMode();
//                    Log.e("AppUtils", "AppUtils isLockedState = "+isLockedState+";isBackground = "+isBackground);
                    if (isBackground || isLockedState) {
                        return true;
                    }else{
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("AppUtils", ""+e);
        }
        return true;
    }
    /**判断当前是否存在活动的activity*/
    public static boolean isBackRunningTask(){
        ActivityManager am = (ActivityManager) BaseApp.getInstance()
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(BaseApp.getInstance().getPackageName())) {
                return true;
            }
        }
 
        return false;
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: