Reputation: 1667
In my code I am trying to understand the intents that get launched when the device is locked.
Eg: Suppose my activity is running, and I press the power button to lock the phone. INTENT.ACTION_SCREEN_OFF is launched. The activity is paused and the screen goes blank.
So what i want is whenever the device is locked by the user i dont want to finish my activity, but if the user press home button or back button i am finishing the activity. So for that i have written a code but its not working.
Code i have used
public void onResume()
{
super.onResume();
m_ScreenLocked = false;
// Intent and receiver to listen to screen lock
m_IntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
m_IntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
m_BroadcastReceiver = new ScreenStateBroadcastReceiver();
registerReceiver(m_BroadcastReceiver, m_IntentFilter);
}
private final class ScreenStateBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, final Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
m_ScreenLocked = true;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
//other stuff
}
}
}
@Override
public void onStop()
{
super.onStop();
m_NoteManagerObject.setPageViewRunning(false);
if (!m_ScreenLocked)
{
unregisterReceiver(m_BroadcastReceiver);
finish();
}
else
{
unregisterReceiver(m_BroadcastReceiver);
}
}
Upvotes: 1
Views: 1340
Reputation: 22647
when you register a receiver programmtically in your activity, it won't get broadcasts when your activity is paused. the docs are fuzzy here as they simply "recommend" unregistering in onPause()
, but do not say that the receiver won't work when your activity is paused.
the real question however is why you want to do that. as a user, i'd be miffed if my screen went off when i was using your app, and when i unlocked the screen, the app was gone. remember that you can't differentiate between the user pressing the power button and the screen simply timing out.
anyway, a possible fix is to register your activity to receive those actions in your manifest. that won't necessarily work though as not all intents can be registered for in a manifest intent filter. if i recall, the ACTION_SCREEN_* intents can't be registered for in your manifest.
another way would be to listen for those intents in a service that is running along side your activity, then be able to send a different intent to your activity to tell it to finish itself.
Upvotes: 1