简体   繁体   English

如何从服务检查活动是否在后台/前台运行?

[英]How to check if an activity is running in background/foreground from a service?

I have created a service which starts from an activity's onCreate and stops on the activity's onDestroy method. 我创建了一个服务,它从一个活动的onCreate开始,并停止在activity的onDestroy方法上。 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? 我怎样才能做到这一点?

  1. 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. 我需要这样做,因为我知道如果任何应用程序被强制关闭或任何类型的崩溃,无法保证调用活动的onDestroy方法。 So, my service which starts when my activity launches won't stop after any crash or any forceful closing event. 因此,我的活动启动时启动的服务不会在任何崩溃或任何有力的结束事件后停止。

  2. I have seen this link where foreground activities can be checked. 我已经看到了可以检查前台活动的链接 But I need to check a running activity in whatever state (either foreground or background) 但我需要在任何状态(前景或后台)检查正在运行的活动

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 首先检查此链接检查Android应用程序是否在后台运行

http://developer.android.com/guide/topics/fundamentals.html#lcycles is 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. 当活动进入后台时,会调用onPause()方法。 So you can deactivate the update notifications in this method. 因此,您可以在此方法中停用更新通知。

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 在清单中加入permisions

<uses-permission android:name="android.permission.GET_TASKS" />

Unfortunately, getRunningTasks() has been deprecated since Android API 21 (Android Lollipop): 不幸的是,自Android API 21(Android Lollipop)以来, getRunningTasks()已被弃用:

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. 此方法在API级别21中已弃用。自LOLLIPOP起,此方法不再适用于第三方应用程序:引入以文档为中心的最近时间意味着它可能会将人员信息泄漏给调用方。 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. 为了向后兼容,它仍将返回其数据的一小部分:至少是调用者自己的任务,以及可能已知不敏感的其他一些任务,如home。

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;
    }

check this link & 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. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用命令检查android服务是在后台还是前台运行? - How to check android service is running in background or foreground using command? 如何检查活动是在Android中的前景还是背景? - How to check whether activity is in foreground or background in android? 如何检查活动是在前景中还是在可见背景中? - How to check if activity is in foreground or in visible background? 如何检查活动是否为前台,并在活动为前台时将其带入后台? - How to check whether a activity is foreground and bring it to background when it is foreground? 如何检查应用程序是否在BroadcastReceiver中的前台后台运行 - How to check app is running in background of foreground in BroadcastReceiver 如何检查Android应用程序是在后台运行还是在前台运行? - How to check if an Android application is running in the background or in foreground? 如果应用程序正在运行,如何检查前台服务? - How to check in foreground service if the app is running? 知道活动是在前台运行还是在后台运行 - Knowing if activity is running on foreground or background 检查活动是否正在从服务运行 - Check if Activity is running from Service 仅当应用程序处于前台状态时才从后台服务启动活动 - Launching an activity from background service only when app is in foreground
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM