简体   繁体   English

Android Service检查用户屏幕是否打开或关闭

[英]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? 有什么方法可以创建可在后台永久运行的服务,以供Android用户检查其屏幕是否打开等。

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. 您可以使用Android广播接收器来检测屏幕的开和关。 Here is a good example of it 这是一个很好的例子

https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/ 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 您也可以按照此线程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. 您不能使用BroadcastReceiver接收屏幕关闭/打开事件。 Write a intent service which is started via boot complete listener and register for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON. 编写一个通过启动完成侦听器启动的Intent服务,并注册Intent.ACTION_SCREEN_OFF和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
         }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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