简体   繁体   中英

Android Service to check whether the user screen on or off

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

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

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

            }
        }
    }

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
         }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM