gpt4 book ai didi

java - 通知 Android : Don't show notification when app is open?

转载 作者:行者123 更新时间:2023-12-02 03:02:02 25 4
gpt4 key购买 nike

我正在开发一个项目,我使用 Intent Service 和wakefulBroadcastReceiver 来安排警报并发送通知。到目前为止还没有问题。但我希望当我打开我的应用程序时,它不会再次显示通知。请问这个问题有什么想法吗?

最佳答案

在通知接收器中,当您收到通知时,您可以检查应用程序是否处于后台,并相应地决定显示通知。

这是检查应用程序是否处于后台的代码。

public class MyGcmPushReceiver extends GcmListenerService {

/**
* Called when message is received.
* @param from SenderID of the sender.
* @param bundle Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
@Override
public void onMessageReceived(String from, Bundle bundle) {
// Check here whether the app is in background or running.
if(isAppIsInBackground(getApplicationContext())) {
// Show the notification
} else {
// Don't show notification
}
}

/**
* Method checks if the app is in background or not
*/
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;
}
}

关于java - 通知 Android : Don't show notification when app is open?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42312167/

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