判断是否在后台或者是否为锁屏状态
private ActivityManager.RunningAppProcessInfo getCurProcess() {
int pid = android.os.Process.myPid();
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess;
}
}
return null;
}
private boolean isBackgroundRunning() {
ActivityManager.RunningAppProcessInfo currentProcess = getCurProcess();
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if(currentProcess != null) {
boolean isBackground = currentProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& currentProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
boolean isLockState = keyguardManager.inKeyguardRestrictedInputMode();
if(isBackground || isLockState) {
return true;
}
}
return false;
}