Android 应用监听亮灭屏状态
时间: 2023-08-05 14:46:46 浏览: 158
要监听 Android 应用的亮灭屏状态,可以使用 BroadcastReceiver 和 Intent 进行实现。具体步骤如下:
1. 在 AndroidManifest.xml 文件中添加权限:
```xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
```
2. 创建一个 BroadcastReceiver 类:
```java
public class ScreenBroadcastReceiver extends BroadcastReceiver {
private boolean isScreenOn = true;
private ScreenStateListener listener;
public ScreenBroadcastReceiver(ScreenStateListener listener) {
this.listener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
isScreenOn = false;
listener.onScreenOff();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
isScreenOn = true;
listener.onScreenOn();
}
}
public boolean isScreenOn() {
return isScreenOn;
}
public interface ScreenStateListener {
void onScreenOn();
void onScreenOff();
}
}
```
3. 注册 BroadcastReceiver:
```java
ScreenBroadcastReceiver screenReceiver = new ScreenBroadcastReceiver(new ScreenBroadcastReceiver.ScreenStateListener() {
@Override
public void onScreenOn() {
// 亮屏时的操作
}
@Override
public void onScreenOff() {
// 熄屏时的操作
}
});
IntentFilter screenFilter = new IntentFilter();
screenFilter.addAction(Intent.ACTION_SCREEN_ON);
screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenReceiver, screenFilter);
```
这样就可以监听 Android 应用的亮灭屏状态了。注意:在不需要监听时,要及时注销 BroadcastReceiver,避免资源浪费。
阅读全文