Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching screen off before is too late

I've an activity that, on its onPause has to do some work but not when the screen is turned off. I've already registered the receiver for the ACTION_SCREEN_OFF intent and, theoretically, this and a static flag at application level should do the trick but... It doesn't work because the onPause callback on the activity is invoked BEFORE the receiver can get its Intent. That is: logcat*ting* while push down the idle button, i can see the onPause trace first and the onReceive after. At this point, setting up the static flag is not very important...

Any possibilities to know at activity's onPause time that the screen has turned off?

Thanks in advance
L.

like image 231
lorenzoff Avatar asked Jan 19 '23 01:01

lorenzoff


1 Answers

I had the same problem and a receiver is not the way to go

android developer

http://developer.android.com/reference/android/content/BroadcastReceiver.html

"Note: If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack."

Instead create a power manager in your onPause method [I got it from this link]

how to find out screen status on an android device?

public void onPause(){

   PowerManager powermanager =(PowerManager)global.getSystemService(Context.POWER_SERVICE); 
   if (powermanager.isScreenOn()){
        screen_off_beforePause = false;
            //your code here
   }else{
    screen_off_beforePause = true;
   }
}

public void onResume() {
   if (screen_off_beforePause){
    Log.e(TAG + ".onResume()", "screen was off before onPause");
   }else{
    Log.d(TAG + ".onResume()", "screen was not off before onPause");
    //your code here
   }

 //resetting
 screen_off_beforePause = false;    
}
like image 195
Rubber Duck Avatar answered Feb 01 '23 06:02

Rubber Duck