Android screen and unlock event broadcast listening

Source: Internet
Author: User

To listen to the screen SCREEN_ON and SCREEN_OFF actions in a program, you can monitor the screen lock status to implement your own functions. The strange thing is that these two actions can only be listened to after they are registered in the form of code, and they cannot be registered in AndroidManifest. xml. I checked it online. It turns out that PowerManager imposes a limit when sending this broadcast. The limit is that only the register can receive the broadcast from the receiver in the code. We hereby record it!

Public class ScreenActionReceiver extends BroadcastReceiver {private String TAG = "ScreenActionReceiver"; private boolean isRegisterReceiver = false; @ Overridepublic void onReceive (Context context, Intent intent) {String action = intent. getAction (); if (action. equals (Intent. ACTION_SCREEN_ON) {Logcat. d (TAG, "unlock broadcast screen... ");} else if (action. equals (Intent. ACTION_SCREEN_OFF) {Logcat. d (TAG, "screen lock broadcast... ");}} Public void registerScreenActionReceiver (Context mContext) {if (! IsRegisterReceiver) {isRegisterReceiver = true; IntentFilter filter = new IntentFilter (); filter. addAction (Intent. ACTION_SCREEN_OFF); filter. addAction (Intent. ACTION_SCREEN_ON); Logcat. d (TAG, "register screen unlock, lock broadcast receiver... "); mContext. registerReceiver (ScreenActionReceiver. this, filter) ;}} public void unRegisterScreenActionReceiver (Context mContext) {if (isRegisterReceiver) {isRegisterReceiver = false; Logcat. d (TAG, "unlock the screen and lock the broadcast receiver... "); mContext. unregisterReceiver (ScreenActionReceiver. this );}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.