android:如何检查应用程序是否在后台2中运行 [英] android:how to check if application is running in background 2
本文介绍了android:如何检查应用程序是否在后台2中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有解决办法.
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;
}
它工作正常.
如何检查我的应用程序是否真正在后台?例如,我打开活动并启动新的活动-标准库(从我的应用程序开始).这个意图是从我的活动开始的,而我的应用程序在逻辑上处于前台.我可以检查自己的活动,但是如何检查这种情况呢?
How I can to check that my application really in background? For example, I opened activity and started new Activity - standard Gallery (started from my application). This intent was started from my activity, and my application logically in foreground. I can check my activities, but how to check this situation too?
并且如何检查应用程序是否从外部活动发送到后台(在此示例中-图库)?
AND how can I check that the application was sent to the background FROM external activity (on this example - gallery)?
推荐答案
public boolean isApplicationSentToBackground(final Context context) {
Boolean flag = false;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= 23) {
List < ActivityManager.RunningTaskInfo > tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
flag = true;
}
}
} else {
try {
Thread.sleep(1500);
flag = false;
List < ActivityManager.RunningAppProcessInfo > runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo: runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
for (String activeProcess: processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
flag = true;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
这篇关于android:如何检查应用程序是否在后台2中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文