HANDLING SCREEN LOCK & UNLOCK BROADCAST EVENTS IN YOUR ANDROID APPLICATION

In Android, we will receive the broadcasted intents for screen lock & unlock. So in onCreate() method we have to set necessary action listeners. Also declare the necessary variables in the corresponding class.




//Declare the necessary variables
private BroadcastReceiver mReceiver;



//add the  below lines of code in to your onCreate() method,
//soon after calling super method.[i.e super.onCreate()]

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);

// Customized BroadcastReceiver class
//Will be defined soon..

mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);







FYI: We will receive Intent.ACTION_SCREEN_ON  action as soon screen is on. i.e It does not mean user has unlocked the screen.


Once we have set the actions which have to be listen to, we now have to define what should happen up on receiving corresponding action-intents. To  handle receivers we define a class which inherits BroadcastReceiver class.






public class ScreenReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent)
{
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
            {    
                  Log.v("$$$$$$", "In Method:  ACTION_SCREEN_OFF");
                  // onPause() will be called.
            }
            else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
            {
                  Log.v("$$$$$$", "In Method:  ACTION_SCREEN_ON");
//onResume() will be called.

//Better check for whether the screen was already locked
// if locked, do not take any resuming action in onResume()

                  //Suggest you, not to take any resuming action here.       
            }
            else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
            {
                  Log.v("$$$$$$", "In Method:  ACTION_USER_PRESENT");
//Handle resuming events
}

      }




Finally,  we have to unregister the action-intents         which ever we have set in onCreate() method. This should be done in onDestroy() of your Activity.




      @Override
      public void onDestroy()
      {
            super.onDestroy();
            Log.v("$$$$$$", "In Method: onDestroy()");
           
            if (mReceiver != null)
            {
                  unregisterReceiver(mReceiver);
                  mReceiver = null;
            }          
         
}





         One more important issue when screen locked is: our current Activity may be stopped forcefully by the system if it finds shortage of memory, instead of moving Activity to background. In such a case, we should have to save (all the necessary data) the current state of the Activity.

         In order to handle this, system will search for onSaveInstanceState() an overridden method before forcefully finishing the current Activity, and during the time of restore, it will call onRestoreInstanceState().




@Override
public void  onSaveInstanceState(Bundle outState)
{
      Log.v("$````$", "In Method: onSaveInstanceState()");
      //if necessary,set a flag to check whether we have to restore or not
      //handle necessary savings…
}

@Override
public void onRestoreInstanceState(Bundle inState)
{
      Log.v("$````$", "In Method: onRestoreInstanceState()");
      //if any saved state, restore from it…
}





That’s it. Happy coding J

15 comments:

  1. hello,

    i am grateful to for this useful article,

    is it possible to lock the android phone screen and unlock it programatically, when the user unlocks,he will have to give password for unlocking, plz put another code example for this scenario

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Excellent blog by my good friend chandan Adiga.

    ReplyDelete
  4. Lock & Unlock is different.
    What you have shown is Screen OFF / ON.

    Phone can be locked while screen is ON....

    ReplyDelete
    Replies
    1. Lock & Unlock can be handled by ACTION_USER_PRESENT only.
      No need to use ACTION_SCREEN_ON or _OFF. When the phone is unlocked by the user then ACTION_USER_PRESENT will catch that the user is present.
      But when the screen is on and the phone is locked then it will not catch that means the user is not present.

      Delete
  5. Correct the Heading First, It is not handling of the lock & unlock.

    ReplyDelete
  6. not handling lock unllock

    ReplyDelete
  7. The above code is not working.. So please update the code

    ReplyDelete
  8. How to handle power button click event using broadcast receiver

    ReplyDelete
  9. How to open an app from lock screen

    ReplyDelete
  10. thanks. Good Solution

    ReplyDelete
  11. Thans for your solution. Could you send me all source which contain this solution on github or another platform ?

    Regards..

    ReplyDelete
  12. Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks.  android pattern unlock

    ReplyDelete
  13. Miracle Thunder Edition 2.82 Tool Without Box Free Download
    https://www.alltips24a2z.com/2019/02/miracle-thunder-edition-282-without-box.html

    ReplyDelete
  14. Thanks for this post, It is really helpful for those who want to unlock screen lock. I am here to tell you my personal experience, my phone got locked during changing network carrier. but using the unlock code, I easily unlocked my phone instantly.

    ReplyDelete