1

I'm writing an app which speaks and listens to the user. Basically an app which allows placing phone calls without having to look or touch the device (believe it or not I didn't find any in the market!). The point here is that I want:

  • to keep running when the screen goes off
  • to stop running when the user switches to another activity

And I don't see an easy way to understand this. I've already looked into this: How to stop a background thread when the screen in android device goes off

but the events are being fired in the wrong order (from my logs):

  • onPause: screen status UNKNOWN
  • onStop: screen status UNKNOWN
  • screen event: OFF

    public class ScreenReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = ScreenStatus.OFF;
            Log.d(TAG,"screen event OFF");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            wasScreenOn = ScreenStatus.ON;
            Log.d(TAG,"screen event ON");
        }
    }
    }
    
Community
  • 1
  • 1
Simone Avogadro
  • 789
  • 8
  • 23
  • I doubt that Screen on off and activity life-cycle methods run in sync with each other. – S.D. Apr 12 '15 at 18:45

1 Answers1

2

Try to use PowerManager as shown in this post, hope it helps. Seems like what you needed,

how to check screen on/off status in onStop()?

Community
  • 1
  • 1
Android Killer
  • 18,174
  • 13
  • 67
  • 90
  • sorry Android Killer: this will _not_ solve my problem. onStop() gets called both if the user navigates away from the app and if the screen goes blank. As described I'm actually asking how to distinguish the two things – Simone Avogadro Apr 12 '15 at 20:15
  • @SimoneAvogadro Edited the answer, please check. This can be done withour BroadcastReceiver i think. – Android Killer Apr 13 '15 at 03:47
  • this is now exactly what I needed. On my reference device it does exactly what I needed. Thanks – Simone Avogadro Apr 13 '15 at 19:40