我正在我的 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
}
}
不要忘记在 manifest.xml 文件中添加 GET_TASKS
权限,以便能够运行 getRunningTasks()
上面代码中的方法:
<uses-permission android:name="android.permission.GET_TASKS" />
p/s : 如果同意这种方式,请注意此权限现已弃用。
关于android - 如何判断 Android 应用程序是否在前台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057573/