简体   繁体   English

记录 Android 用户唤醒/解锁

[英]Log Android user wakeup/unlock

I'm trying to create an application that has a constant running service which will log and display to the user everytime they unlock or change the phones state from screen off to screen on.我正在尝试创建一个具有持续运行服务的应用程序,该服务将在用户每次解锁或将手机状态从屏幕关闭更改为屏幕打开时记录并显示给用户。 Is this possible without using the Log cat through the PC?如果不通过 PC 使用 Log cat,这可能吗?

Yes you can do it using Broadcast Receiver. 是的,您可以使用广播接收器进行操作。 Android system sends always broadcasts for specified changes. Android系统始终针对指定更改发送广播。 You can handle this broadcasts using Broadcast Receiver. 您可以使用广播接收器处理此广播。

Example: 例:

We will create a new Broadcast Receiver to handle the Screen On and Screen Off state: 我们将创建一个新的广播接收器以处理屏幕打开和屏幕关闭状态:

    public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
        //we will handle here the activities which will tell us that
        // the screen state has changed
        if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
           //write log that the screen is off
        }else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
           //write log that the screen is on
        }
      }
   }

All what you need is to declare this BroadcastReceiver in Android Manifest.xml file: 您所需要做的就是在Android Manifest.xml文件中声明此BroadcastReceiver:

 <receiver android:name="yourpackage.PhoneStateBroadcastReceiver">
        <intent-filter>
        </intent-filter>
 </receiver>

And after that you should start your PhoneStateBroadcastReceiver on yout Service onCreate Method: 然后,您应该在服务onCreate方法上启动PhoneStateBroadcastReceiver:

//...
public void onCreate(){
   IntentFilter filter = new IntentFilter();
   filter.addAction(Intent.ACTION_SCREEN_OFF);
   filter.addAction(Intent.ACTION_SCREEN_ON);

   PhoneStateBroadcastReceiver pSReciever = new PhoneStateBroadcastReceiver();
   registerReceiver(pSReciever, filter);
}

Did you ever implement this?你有没有实现过这个? I would like an app that simply shows a history of timestamps for when the screen changes state.我想要一个应用程序,它只显示屏幕更改状态时的时间戳历史记录。 Just that.只是。

I can do a bit of coding myself, it's just setting up the whole app development environment is daunting.我可以自己做一些编码,只是设置整个应用程序开发环境是令人生畏的。

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

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