You can store your boolean value in shared preferences, that way it stays persistent in memory even if you switch Activities. For example: when you want to unlock your app (for example in onStop()) you can just set it to false with this method:
public void setLockStatus(boolean lock) {
getSharedPreferences("SOMETAG", 0).edit().putBoolean("LOCK", lock)
.commit();
}
Later when you want to check if your app is locked (maybe in onStart of next activity):
public boolean getLockStatus() {
return getSharedPreferences("SOMETAG", 0).getBoolean("LOCK", true);
}
Also note that this method will return true if no "LOCK" value has been set (as indicated by the second param to getBoolean).
So every Activity that you have when it starts checks our flag if the App is locked.
@Override
public void onStart() {
super.onStart();
if (getLockStatus() == true) {
// show lockscreen
} else {
// we are not locked.
}
}
Now we need one more flag to check if we are still in the App and never left:
public void setAppStatus(boolean status) {
getSharedPreferences("SOMETAG", 0).edit().putBoolean("IN_APP", status)
.commit();
}
public boolean getAppStatus() {
return getSharedPreferences("SOMETAG", 0).getBoolean("IN_APP", false);
}
So now every time we launch a new activity before we start it we have to set a flag that we are still in the App, so that onStop will know that we shouldn't lock the app. For example if your button onClick start a new Activity in the onClick we can do this:
@Override
public void onClick(View v) {
setAppStatus(true); // we are not leaving the app.
// startActivity(blabla);
}
Now onStop checks if we need to lock:
@Override
public void onStop() {
super.onStop();
if(getAppStatus() == false) setLockStatus(true); // locking the app
else setLockStatus(false);
}
EDIT: also you need to setAppStatus(false); if you are actually leaving the application.
Hope this gives you an idea of how to solve it, you need to implement the back press logic yourself (when to lock the app and when not to).