在 Android 中判断手机黑屏和判断 APP 在后台运行的方式如下:
1. 判断手机黑屏
可以通过监听设备的屏幕状态来判断手机是否黑屏。具体的实现方式是监听 ACTION_SCREEN_OFF
和 ACTION_SCREEN_ON
这两个广播,代码示例如下:
public class ScreenStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
// 屏幕关闭,手机黑屏
Log.d("ScreenStateReceiver", "屏幕已关闭(黑屏)");
} else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
// 屏幕开启
Log.d("ScreenStateReceiver", "屏幕已开启");
}
}
}
// 在 Activity 或 Service 中注册广播接收器
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(new ScreenStateReceiver(), filter);
2. 判断 APP 在后台运行
要判断 APP 是否在后台运行,可以使用以下几种方法:
方法 1: 通过 ActivityManager
可以利用 ActivityManager
获取当前运行的任务和顶层的活动:
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
boolean isInBackground = true;
for (ActivityManager.RunningAppProcessInfo appProcess : runningApps) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(context.getPackageName())) {
isInBackground = false;
break;
}
}
if (isInBackground) {
Log.d("AppState", "APP在后台运行");
} else {
Log.d("AppState", "APP在前台运行");
}
方法 2: 使用 LifecycleObserver
在 Android Jetpack 的 Lifecycle 组件中,可以使用 LifecycleObserver
来观察应用的状态:
public class MyAppLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnterBackground() {
Log.d("Lifecycle", "应用进入后台");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnterForeground() {
Log.d("Lifecycle", "应用进入前台");
}
}
// 在 Application 类中注册
ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyAppLifecycleObserver());
总结
- 通过广播接收器可以监测屏幕状态以判断黑屏。
- 通过
ActivityManager
和LifecycleObserver
可以判断 APP 是否在后台运行。