How to stop the service when ACTION_SCREEN_OFF

I'm trying to turn off my UpdateService for my digital clock widget when the screen is off to save the battery, and then turn it on again when the screen is activated. I am currently using it in my onReceive () in my AppWidgetProvider application, but I also tried it in BroadcastReciever.

My current code is:

public static boolean wasScreenOn = true;

public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
    Log.d("Screen switched on. ", "Starting DigiClock UpdateService.");
    context.startService(new Intent(UpdateService2by2.ACTION_UPDATE));
    wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
    Log.d("Screen switched off. ", "Stopping DigiClock UpdateService.");
    context.stopService(new Intent(context, UpdateService2by2.class));
    wasScreenOn = true;
}

Can anyone help me here? I'm at a dead end.

+3
source share
4 answers

I am sure you need to register your receiver in code for ACTION_SCREEN_OFF/ON. I do not think that registering them in the manifest will work.

+3
source

, ACTION_SCREEN_ON/OFF . BroadcastReceiver . . .

, . , SCREEN_ON. ACTION_BATTERY_CHANGED.

, , , , .

+1

, , . , .

, BroadcastReceiver ; .

, , , - onCreate():

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver screenoffReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
      Log.v("screenoffReceiver", "SCREEN OFF");
    }
    else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
      Log.v("screenoffReceiver", "SCREEN ON");
    }
    return;
  }
};      
registerReceiver(screenoffReceiver, filter);

, onPause()/onResume() , / , , -, , onPause() onResume(), , , , ( ), BroadcastReceiver.

; , , , , , , . setVisibility (VISIBLE) onResume() .

, , , - BroadcastReceiver, onPause() / onResume(), , .

+1
source

Perhaps you should use

public class MyReceiver extends BroadcastReceiver {..}

And then use this class name in the manifest

0
source

Source: https://habr.com/ru/post/1781923/


All Articles