本文介绍了如何在Kitkat(4.4)中后台识别应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在后台运行时检测应用程序.一切正常,但在New Android Version 4.4(Kitkat)
中不起作用.我无法找到Kitkat
的问题.它总是返回false
.
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;
}
推荐答案
我遇到了同样的问题.解决方法是在onStop()上调用此方法.
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;
}
}
这篇关于如何在Kitkat(4.4)中后台识别应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!