In the video player, encountered a problem, after the user plays the video and then lock screen, the video player is still playing, encountered a similar phone system status changes in the time, the first thought of the broadcast, the following is a summary:
Public classScreenlistener {PrivateContext Mcontext; PrivateScreenbroadcastreceiver Mscreenreceiver; PrivateScreenstatelistener Mscreenstatelistener; PublicScreenlistener (Context context) {Mcontext=context; Mscreenreceiver=NewScreenbroadcastreceiver (); } /*** Screen status broadcast recipient*/ Private classScreenbroadcastreceiverextendsBroadcastreceiver {PrivateString action =NULL; @Override Public voidOnReceive (Context context, Intent Intent) {action=intent.getaction (); if(Intent.ACTION_SCREEN_ON.equals (ACTION)) {//Open ScreenMscreenstatelistener.onscreenon (); } Else if(Intent.ACTION_SCREEN_OFF.equals (ACTION)) {//Lock ScreenMscreenstatelistener.onscreenoff (); } Else if(Intent.ACTION_USER_PRESENT.equals (ACTION)) {//Unlockmscreenstatelistener.onuserpresent (); } } } /*** Start listening to screen status * *@paramListener*/ Public voidbegin (Screenstatelistener listener) {Mscreenstatelistener=Listener; Registerlistener (); Getscreenstate (); } /*** Get screen status*/ Private voidgetscreenstate () {PowerManager Manager=(PowerManager) mcontext. Getsystemservice (Context.power_service); if(Manager.isscreenon ()) {if(Mscreenstatelistener! =NULL) {Mscreenstatelistener.onscreenon (); } } Else { if(Mscreenstatelistener! =NULL) {Mscreenstatelistener.onscreenoff (); } } } /*** Stop screen status monitoring*/ Public voidUnregisterlistener () {mcontext.unregisterreceiver (mscreenreceiver); } /*** Start screen status broadcast receiver*/ Private voidRegisterlistener () {intentfilter filter=NewIntentfilter (); Filter.addaction (intent.action_screen_on); Filter.addaction (Intent.action_screen_off); Filter.addaction (intent.action_user_present); Mcontext.registerreceiver (mscreenreceiver, filter); } Public InterfaceScreenstatelistener {//return to caller screen state information Public voidOnscreenon (); Public voidOnscreenoff (); Public voidonuserpresent (); }}
In the above code, the use of dynamic registration broadcast, in the activity that needs to monitor the state of the screen, when there is no need to listen, such as activity finish, the use of Unregisterlistener to release the broadcast monitoring; The following is called in the activity;
Screenlistener L =NewScreenlistener ( This); L.begin (NewScreenstatelistener () {@Override Public voidonuserpresent () {LOG.E ("Onuserpresent", "Onuserpresent"); } @Override Public voidOnscreenon () {LOG.E ("Onscreenon", "Onscreenon"); } @Override Public voidOnscreenoff () {LOG.E ("Onscreenoff", "Onscreenoff"); } });
Through the above steps, the monitoring of the screen state is realized.
Android Monitor Screen lock screen & user unlock