在android中获取解锁事件的方法?

时间:2013-11-26 18:03:43

标签: android broadcastreceiver lockscreen

有没有办法接收类似PHONE_UNLOCKED(某种BroadcastReceiver)的内容?

我运行的服务在屏幕打开时显示Toast。不幸的是,一些手机在解锁之前不会显示它。大多数时候Toast消息已经消失了。

1 个答案:

答案 0 :(得分:45)

广播接收器操作 ACTION_USER_PRESENT 这里是ACTION_USER_PRESENT和ACTION_SHUTDOWN的实现

将此添加到您的应用清单

<receiver android:name=".UserPresentBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.USER_PRESENT" />
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
 </intent-filter>
</receiver>

接收行动

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class UserPresentBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent intent) {

        /*Sent when the user is present after 
         * device wakes up (e.g when the keyguard is gone)
         * */
        if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

        }
        /*Device is shutting down. This is broadcast when the device 
         * is being shut down (completely turned off, not sleeping)
         * */
        else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {

        }
    }

}

更新:

作为Android 8.0(API级别26)后台执行限制的一部分,针对API级别26或更高级别的应用程序无法再在其清单中为隐式广播注册广播接收器。 see