首页 > 代码库 > BroadcastReceiver之屏幕锁屏和解锁监听

BroadcastReceiver之屏幕锁屏和解锁监听

对于解锁和锁屏这种用的比较频繁action,谷歌做了限制,必须手动用代码注册

直接上代码:这是注册广播

 1 public class MainActivity extends AppCompatActivity {
 2     Screen screen;
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7 
 8         screen = new Screen();
 9         IntentFilter filter = new IntentFilter();
10         //添加action
11         filter.addAction("android.intent.action.SCREEN_OFF");
12         filter.addAction("android.intent.action.SCREEN_ON");
13         //注册广播接收者
14         this.registerReceiver(screen,filter);
15     }
16 
17     @Override
18     protected void onDestroy() {
19         super.onDestroy();
20         unregisterReceiver(screen);
21     }

 

 1 public class Screen extends BroadcastReceiver {
 2     @Override
 3     public void onReceive(Context context, Intent intent) {
 4         String action = intent.getAction();
 5         if (action.equals("android.intent.action.SCREEN_OFF")){
 6             System.out.println("屏幕锁屏了");
 7         }else if (action.equals("android.intent.action.SCREEN_ON")){
 8             System.out.println("屏幕解锁了");
 9         }
10     }
11 }

 

BroadcastReceiver之屏幕锁屏和解锁监听