可以使用BroadcastReceiver和PowerManager实现。代码示例如下:
创建BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// 屏幕关闭
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
// 屏幕打开
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
// 解锁屏幕
}
}
}
创建服务:
public class ScreenService extends Service {
private ScreenReceiver mScreenReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mScreenReceiver = new ScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mScreenReceiver, filter);
return START_STICKY;
}
@Override
public void onDestroy() {
unregisterReceiver(mScreenReceiver);
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在AndroidManifest.xml文件中声明服务:
在应用程序中启动服务:
Intent intent = new Intent(this, ScreenService.class);
startService(intent);
这样就可以检测屏幕的状态了。当屏幕关闭、打开或解锁时,BroadcastReceiver会接收到相应的Intent。