-1

I'm trying to work a piece of code that works so that when the user turns on the screen, an event or piece of code is called and ran. This needs to work when the screen goes to sleep as well and should have a cancel feature to stop this occuring at the users command. Could anyone suggest any ideas on how to code this in android

  • 1
    possible duplicate of [android: broadcast receiver for screen on and screen off](http://stackoverflow.com/questions/9477922/android-broadcast-receiver-for-screen-on-and-screen-off) – indivisible May 29 '14 at 19:15

1 Answers1

0

If you want to do something when your Activity become foreground or background you can override onWindowFocusChanged,

public void onWindowFocusChanged(boolean hasFocus){
    if(hasFocus){
        //activity become foreground
    }
    else{
       //activity become background
    }
}

If you want to do something just based on screen state, regardless of your applications activity visible or not than you need to use a BroadcastReceiver but still need a service or activity running on the background check out this question android: broadcast receiver for screen on and screen off

Community
  • 1
  • 1
Onur
  • 5,617
  • 3
  • 26
  • 35