如何检查Android应用程序是在后台还是前台或终止()

满堂花醉三千客,一剑霜寒十四州。这篇文章主要讲述如何检查Android应用程序是在后台还是前台或终止?相关的知识,希望能为你提供帮助。
我想检查我的应用程序状态,现在很容易我使用下面的代码在后台或前台获取我的应用程序,但我不知道如何检查应用程序被杀或终止任何人都可以帮助解决此问题。使用下面的代码,我在后台或前台检查应用程序。

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

答案这是完美的代码并检查onStop方法
private 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; }

另一答案【如何检查Android应用程序是在后台还是前台或终止()】如果您的minSDK是14+,则普遍的共识似乎是在实现ActivityLifecycleCallbacks(https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html)的类中使用计数器。有一个YouTube视频,描述了Firebase如何使用这种技术here。

    推荐阅读