这对于 Android 来说确实是一个有问题的案例。尝试以下对我有用的方法:
为您的活动创建一个基类。在里面:
@Override
protected void onPause() {
Utils.wentInBackground(this);
super.onPause();
}
@Override
protected void onResume() {
Utils.wentInForeground(this);
super.onResume();
}
然后在静态实用程序类中有这个:
public static void wentInBackground(final Activity which) {
inBackground = true;
lastPaused = which.getClass().getSimpleName();
final PowerManager powerManager = (PowerManager) which.getSystemService(POWER_SERVICE);
final boolean isScreenOn = powerManager.isScreenOn();
if (isApplicationSentToBackground(which) || !isScreenOn) {
// Do your security lockdown here.
}
}
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
public static void wentInForeground(final Activity which) {
inBackground = false;
final String activityName = which.getClass().getSimpleName();
if (lastPaused.equals(activityName) || !isLoggedIn()) {
if (isLoggedIn()) {
// Do your security lockdown here again, if necessary.
}
// Show your security screen or whatever you need to.
}
}
public static boolean isLoggedIn() {
return loggedIn;
}