4

BroadcastReceiver之实现锁屏、解锁例子

 3 years ago
source link: https://blog.csdn.net/ljphhj/article/details/38842733
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

BroadcastReceiver之实现锁屏、解锁例子

好久没有写android的小例子了,由于前几天写了一篇关于Intent.Action的文章(http://blog.csdn.net/ljphhj/article/details/38796739),有朋友私信问我关于ACTION_SCREEN_ON和ACTION_SCREEN_OFF还有ACTION_USER_PRESENT三个Action的用法,由于作为一个总结博文,当时并没有详细讲,ACTION_SCREEN_ON和ACTION_SCREEN_OFF只能通过动态注册的方式(代码内context.register和unregister),而ACTION_USER_PRESENT则是动态、静态注册两种方式都可以。下面我们通过这个锁屏、解锁相关的BroadcastReceiver来了解一下。

LogCat结果图:

由于是静态注册的方式,所以大家可能会觉得那我要怎么让它长久地监听这锁屏、解锁屏幕的广播呢?

首先我们再次强调ACTION_SCREEN_ON和ACTION_SCREEN_OFF只能通过动态注册的方式(代码内context.register和unregister),而ACTION_USER_PRESENT则是动态、静态注册两种方式都可以。

那么我们的突破口便是:我们可以动态地注册一个关于屏幕解锁后(ACTION_USER_PRESENT)的广播者,并且在这个广播的onReceive方法中实现我们要做的一些操作。例如我们可以开启一个Service服务,用于注册我们所想要的这个Broadcast Receiver

1.在Service中定义receiver

  1. private BroadcastReceiver mScreenFilterReceiver = new BroadcastReceiver() {  
  2.     public void onReceive(Context context, Intent intent) {  
  3.             if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {  
  4.                 //做要求的处理  
  5.             }else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){

2.在Service的onCreate中定义IntentFilter及注册receiver

  1. IntentFilter ScreenFilter = new IntentFilter();  
  2. ScreenFilter.addAction(Intent.ACTION_SCREEN_ON);  
  3. ScreenFilter.addAction(Intent.ACTION_SCREEN_OFF); 
  4. registerReceiver(mScreenFilterReceiver, ScreenFilter);  

3.在Service的onDestroy中要反注册这个receiver。

  1. unregisterReceiver(mScreenFilterReceiver);  

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK