问题
I am trying to detect app when it goes in background. Everything works perfect but in New Android Version 4.4(Kitkat)
its not working. I am unable to find out what's the issue with Kitkat
. It always returns false
.
public static boolean inBackground(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;
}
回答1:
Override Activity.onPause() or Activity.onStop(), depending on which level of background you want.
回答2:
I'm having the same problem. The solution is to call this method on onStop().
To simplify, I extend the Activities where I need to detect when app goes to background to class below.
public abstract class MyActivity extends Activity {
@Override
public void onStop() {
super.onStop();
if (isApplicationSentToBackground(this)){
// handle app going into background here
}
}
private 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;
}
}
来源:https://stackoverflow.com/questions/20500432/how-to-identify-app-when-it-goes-in-background-in-kitkat-4-4