Для прослушивания включения / выключения экрана ваше приложение должно запускаться по времени и программно регистрировать Broadcast receiver
для ОС.
ScreenOnOffService.java
public class ScreenOnOffService extends Service {
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.i("ScreenOnOffService", "onCreate: ");
IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
}
public void onDestroy() {
super.onDestroy();
Log.i("ScreenOnOffService", "onDestroy: ");
unregisterReceiver(ScreenOnReceiver.newInstance());
// startService(new Intent(this,ScreenOnOffService.class));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
ScreenOnReceiver.java
public class ScreenOnReceiver extends BroadcastReceiver {
public static final String TAG = "ScreenOn";
public static volatile ScreenOnReceiver screenOn;
public static ScreenOnReceiver newInstance() {
if (screenOn == null) {
screenOn = new ScreenOnReceiver();
}
return screenOn;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("hieuN", "intent: " + intent.getAction());
// do work. start activity.
}
}
Запуск службы в действии
Intent service = new Intent(this, ScreenOnOffService.class);
startService(service);