Запустите службу в фоновом режиме с уведомлением, и внутренний экран обнаружения службы заблокирован или нет. // createAndShowForegroundNotification создаст уведомление, которое // не может быть отменено. затем зарегистрируйте фильтр намерений и не забудьте отменить регистрацию при // уничтожении
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
createAndShowForegroundNotification(BackgroundSyncService.this, 9797);
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mScreenReceiver = new ScreenReceiver();
this.registerReceiver(mScreenReceiver, filter);
return START_STICKY;
}
// это приемник, который будет вызываться при выключенном освещении экрана внутри службы
открытый класс ScreenReceiverрасширяет BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
} else{
}
}
}