gpt4 book ai didi

android - 如何判断应用程序是否在后台?

转载 作者:行者123 更新时间:2023-11-29 01:28:53 24 4
gpt4 key购买 nike

我有以下方法不能准确地用于 Lollipop 代码段。 getRunningAppProcesses() 方法返回各种系统任务,还返回多个结果,我无法确定哪个结果代表使用 getRunningTasks(1).get(0).topActivity 的等价物

对于 API 21 及更高版本,这应该如何完成?

   public static boolean isAppInBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
if (!tasks.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo fullTaskList : tasks) {
if (fullTaskList.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// NOTE: this condition needs to be changed because
// the list returns multiple results and not all
// the results represent IMPORTANCE_BACKGROUND
return true;
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
}
return false;
}

最佳答案

我找到的最简单直接的解决方案如下:

public class AppStatusHelper {
private static final String TAG = AppStatusHelper.class.getSimpleName();

private static int mNumOfActivitiesInOnStarttoOnStopLifeCycle=0;

public static void onStart()
{
mNumOfActivitiesInOnStarttoOnStopLifeCycle++;
}
public static void onStop()
{
mNumOfActivitiesInOnStarttoOnStopLifeCycle--;
}

public static boolean isAppInBackground()
{
Log.d(TAG,"num->"+mNumOfActivitiesInOnStarttoOnStopLifeCycle+"\tisOnBackground->"+(mNumOfActivitiesInOnStarttoOnStopLifeCycle==0));
return mNumOfActivitiesInOnStarttoOnStopLifeCycle==0;
}

}

只需在每次 Activity 开始时调用 onStart 并在每次 Activity 停止时调用 onStop。然后检查计数器是否等于0。

关于android - 如何判断应用程序是否在后台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32365356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com