Android Screen Lock-Unlock Intents
Android Screen Lock-Unlock Intents
Chandan Adiga
http://www.chandan-tech.blogspot.com
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.
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
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.
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
Log.d("DUBUG”, "In Method: ACTION_SCREEN_OFF");
// onPause() will be called.
-1
HANDLING SCREEN LOCK AND UNLOCK IN ANDROID
Chandan Adiga
http://www.chandan-tech.blogspot.com
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Log.d("DUBUG", "In Method: ACTION_SCREEN_ON");
//onResume() will be called.
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.d("DUBUG", "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.
-2
HANDLING SCREEN LOCK AND UNLOCK IN ANDROID
Chandan Adiga
http://www.chandan-tech.blogspot.com
@Override
public void onSaveInstanceState(Bundle outState)
{
Log.d("DUBUG", "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.d("$DUBUG", "In Method: onRestoreInstanceState()");
//if any saved state, restore from it…
}
-3