0

Is there any way to create a service that runs forever on a background for Android user to check whether their screen on or off, etc?

I'm about to create an analytics, so I need to know when the user turn on or turn off their screen.

Thanks, I will appreciate all the input

Webster
  • 1,113
  • 2
  • 19
  • 39
  • 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) – X3Btel Mar 15 '17 at 10:50

3 Answers3

1

You may use Android broadcast receiver to detect screen on and off. Here is a good example of it

https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

you may also follow this thread https://stackoverflow.com/a/9478013/2784838

Community
  • 1
  • 1
Junaid Hafeez
  • 1,618
  • 1
  • 16
  • 25
1

You need to create broadcast receiver and manage screen on or off status.

     Declare receiver in manifest:    
     <receiver android:name=".DeviceWakeUpReceiver" />


    public class DeviceWakeUpReceiver extends BroadcastReceiver {
        private static final String TAG = "DeviceWakeUpService";
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive() called");
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                //End service when user phone screen off

            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                //Start service when user phone screen on

            }
        }
    }
Jd Prajapati
  • 1,953
  • 13
  • 24
-1

You cannot use a BroadcastReceiver for receiving screen off/on events. Write a intent service which is started via boot complete listener and register for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON.

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new ScreenOffOnReceiver(), filter);

class ScreenOffOnReiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
         if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
             // Screen OFF
         else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
             // Screen ON
         }
    }
}
vikesh
  • 31
  • 4