android屏幕加解锁事件广播的监听

http://blog.csdn.net/a443453087/article/details/8198859


      想在程序中监听屏幕SCREEN_ON和SCREEN_OFF这两个action,实现屏幕锁定状态的监听,从而实现自己的相应功能。比较奇怪的是这两个action只能通过代码的形式注册才能被监听到,在AndroidManifest.xml中注册根本监听不到。去网上查了一下,原来是PowerManager那边在发这个广播的时候做了限制,限制只有register到代码中的receiver才能接收。特此记录!

 

 

 

[html]  view plain copy
  1. public class ScreenActionReceiver extends BroadcastReceiver {  
  2.   
  3.     private String TAG = "ScreenActionReceiver";  
  4.     private boolean isRegisterReceiver = false;  
  5.   
  6.     @Override  
  7.     public void onReceive(Context context, Intent intent) {  
  8.         String action = intent.getAction();  
  9.         if (action.equals(Intent.ACTION_SCREEN_ON)) {  
  10.             Logcat.d(TAG, "屏幕解锁广播...");  
  11.         } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {  
  12.             Logcat.d(TAG, "屏幕加锁广播...");  
  13.         }  
  14.     }  
  15.   
  16.     public void registerScreenActionReceiver(Context mContext) {  
  17.         if (!isRegisterReceiver) {  
  18.             isRegisterReceiver = true;  
  19.   
  20.             IntentFilter filter = new IntentFilter();  
  21.             filter.addAction(Intent.ACTION_SCREEN_OFF);  
  22.             filter.addAction(Intent.ACTION_SCREEN_ON);  
  23.             Logcat.d(TAG, "注册屏幕解锁、加锁广播接收者...");  
  24.             mContext.registerReceiver(ScreenActionReceiver.this, filter);  
  25.         }  
  26.     }  
  27.   
  28.     public void unRegisterScreenActionReceiver(Context mContext) {  
  29.         if (isRegisterReceiver) {  
  30.             isRegisterReceiver = false;  
  31.             Logcat.d(TAG, "注销屏幕解锁、加锁广播接收者...");  
  32.             mContext.unregisterReceiver(ScreenActionReceiver.this);  
  33.         }  
  34.     }  
  35.   
  36. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值