I want to lock my application when it goes in background and when it resumes I want to display my own lock screen. The lock screen is an Activity of my application.
Aft
The principal problem is that you have to get a specific behavior when you start an Activity
from the background. onPause()
and onResume()
are called every time you switch between Activities
and not just when you minimize your application. To get around that you can get the currently running tasks from the ActivityManager
and compare their package name to the one of your application:
private boolean isApplicationInBackground() {
final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List tasks = manager.getRunningTasks(1);
if (!tasks.isEmpty()) {
final ComponentName topActivity = tasks.get(0).topActivity;
return !topActivity.getPackageName().equals(getPackageName());
}
return false;
}
Now you can do this:
public boolean wasPaused = false;
@Override
public void onPause() {
super.onPause();
if(isApplicationInBackground()) {
wasPaused = true;
}
}
@Override
public void onResume() {
super.onResume();
if(wasPaused) {
lockScreen();
wasPaused = false;
}
}
And that is it! I recommend you implement this in a base Activity
which all your other Activities
inherent from.