歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android屏幕加解鎖事件廣播的監聽

Android屏幕加解鎖事件廣播的監聽

日期:2017/3/1 10:07:06   编辑:Linux編程

想在程序中監聽屏幕SCREEN_ON和SCREEN_OFF這兩個action,實現屏幕鎖定狀態的監聽,從而實現自己的相應功能。比較奇怪的是這兩個action只能通過代碼的形式注冊才能被監聽到,在AndroidManifest.xml中注冊根本監聽不到。去網上查了一下,原來是PowerManager那邊在發這個廣播的時候做了限制,限制只有register到代碼中的receiver才能接收。特此記錄!

  1. public class ScreenActionReceiver extends BroadcastReceiver {
  2. private String TAG = "ScreenActionReceiver";
  3. private boolean isRegisterReceiver = false;
  4. @Override
  5. public void onReceive(Context context, Intent intent) {
  6. String action = intent.getAction();
  7. if (action.equals(Intent.ACTION_SCREEN_ON)) {
  8. Logcat.d(TAG, "屏幕解鎖廣播...");
  9. } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
  10. Logcat.d(TAG, "屏幕加鎖廣播...");
  11. }
  12. }
  13. public void registerScreenActionReceiver(Context mContext) {
  14. if (!isRegisterReceiver) {
  15. isRegisterReceiver = true;
  16. IntentFilter filter = new IntentFilter();
  17. filter.addAction(Intent.ACTION_SCREEN_OFF);
  18. filter.addAction(Intent.ACTION_SCREEN_ON);
  19. Logcat.d(TAG, "注冊屏幕解鎖、加鎖廣播接收者...");
  20. mContext.registerReceiver(ScreenActionReceiver.this, filter);
  21. }
  22. }
  23. public void unRegisterScreenActionReceiver(Context mContext) {
  24. if (isRegisterReceiver) {
  25. isRegisterReceiver = false;
  26. Logcat.d(TAG, "注銷屏幕解鎖、加鎖廣播接收者...");
  27. mContext.unregisterReceiver(ScreenActionReceiver.this);
  28. }
  29. }
  30. }
Copyright © Linux教程網 All Rights Reserved