gpt4 book ai didi

android - 如何判断 Android 应用程序是否在前台运行?

转载 作者:IT老高 更新时间:2023-10-28 13:09:19 28 4
gpt4 key购买 nike

我正在我的 android 应用程序中执行由 c2dm 触发的状态栏通知。如果应用程序正在运行,我不想显示通知。您如何确定应用程序是否正在运行并处于前台?

最佳答案

或者,您可以使用 ActivityManager 通过 getRunningTasks 方法检查正在运行的任务。然后检查返回的任务列表中的第一个任务(前台任务),如果它是您的任务。
下面是代码示例:

public Notification buildNotification(String arg0, Map<String, String> arg1) {

ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager
.getRunningTasks(Integer.MAX_VALUE);
boolean isActivityFound = false;

if (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(appContext.getPackageName().toString())) {
isActivityFound = true;
}

if (isActivityFound) {
return null;
} else {
// write your code to build a notification.
// return the notification you built here
}

}

并且不要忘记在 ma​​nifest.xml 文件中添加 GET_TASKS 权限,以便能够运行 getRunningTasks()上面代码中的方法:

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

p/s : 如果同意这种方式,请注意此权限现已弃用。

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

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