Android 如何从服务检查活动是否在后台/前台运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21850485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an activity is running in background/foreground from a service?
提问by CrazyLearner
I have created a service which starts from an activity's onCreate and stops on the activity's onDestroy method. Now I have to check from a method of the service that whether the activity is running in foreground/background(for some cases like application is forcefully closed). How can I do that?
我创建了一个从活动的 onCreate 开始并在活动的 onDestroy 方法上停止的服务。现在我必须从服务的方法中检查活动是否在前台/后台运行(对于某些情况,例如应用程序被强行关闭)。我怎样才能做到这一点?
I need to do this coz as far I know there is no guarantee of calling onDestroy method of an activity if any the application is forcefully closed or any kind of crash. So, my service which starts when my activity launches won't stop after any crash or any forceful closing event.
I have seen this linkwhere foreground activities can be checked. But I need to check a running activity in whatever state (either foreground or background)
我需要这样做,因为据我所知,如果任何应用程序被强行关闭或任何类型的崩溃,都不能保证调用活动的 onDestroy 方法。因此,在我的活动启动时启动的服务不会在任何崩溃或任何强制关闭事件后停止。
我已经看到了可以检查前台活动的链接。但是我需要检查处于任何状态(前台或后台)的正在运行的活动
回答by Hassaan Rabbani
Final Update
最终更新
To check for all activities:
要检查所有活动:
@Override
protected void onStop() {
super.onStop();
if (AppConstants.isAppSentToBackground(getApplicationContext())) {
// Do what ever you want after app close simply Close session
}
}
Method to check our app is running or not:
检查我们的应用程序是否正在运行的方法:
public static boolean isAppSentToBackground(final Context context) {
try {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground
// task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity
.getPackageName();// get the top fore ground activity
PackageManager pm = context.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo
.loadLabel(pm).toString();
// Log.e("", foregroundTaskAppName +"----------"+
// foregroundTaskPackageName);
if (!foregroundTaskAppName.equals("Your App name")) {
return true;
}
} catch (Exception e) {
Log.e("isAppSentToBackground", "" + e);
}
return false;
}
Answer updated again
答案再次更新
Use the below method with your package name.It will return true if any of your activity is in foreground.
将以下方法与您的包名称一起使用。如果您的任何活动在前台,它将返回 true。
public boolean isForeground(String myPackage){
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) return true;
return false;
}
Answer Updated
答案更新
Check this link first Checking if an Android application is running in the background
http://developer.android.com/guide/topics/fundamentals.html#lcyclesis a description of the Life Cycle of an android application.
http://developer.android.com/guide/topics/fundamentals.html#lcycles是对 android 应用程序生命周期的描述。
The method onPause() gets called when the activity goes into the background. So you can deactivate the update notifications in this method.
当活动进入后台时调用 onPause() 方法。因此,您可以在此方法中停用更新通知。
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;
}
add permisions in the menifest as well
也在清单中添加权限
<uses-permission android:name="android.permission.GET_TASKS" />
回答by Sam Lu
Unfortunately, getRunningTasks()
has been deprecated since Android API 21 (Android Lollipop):
不幸的是,getRunningTasks()
自 Android API 21 (Android Lollipop) 以来已被弃用:
This method was deprecated in API level 21. As of LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.
此方法在 API 级别 21 中已弃用。从 LOLLIPOP 开始,此方法不再可用于第三方应用程序:引入以文档为中心的最近记录意味着它可能会将个人信息泄露给调用者。为了向后兼容,它仍将返回其数据的一小部分:至少是调用者自己的任务,可能还有一些其他任务,例如已知不敏感的 home。
回答by Yessine Mahdouani
Try this method to check your app is in background or not:
试试这个方法来检查你的应用程序是否在后台:
public boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
回答by i.n.e.f
check thislink & especially check the Answer Which shows this part of code
检查此链接,特别是检查显示这部分代码的答案
public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
Hope this help you.
希望这对你有帮助。