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

标签 java android android-intentservice

我正在开发一个项目,我使用 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/

相关文章:

java - 在 JLayeredPane 上添加两个 JPanel 后没有任何输出

java - LazyList 的 listview 无法使用新的 arraylist 刷新

android - 使用定时器重复 IntentService - 是否可取?

java - 扫描仪不接受另一个字符串的输入并跳过它

java - 如何从 Java 中的给定字符串中删除注释?

android - 如何将我的应用程序的内部存储的读/写权限授予 TextToSpeech/MediaPlayer?

android自动检测图像中的文档边缘并裁剪

Android - 多次运行 IntentService

android - 在 onReceive 中处理多个 intent.getStringExtra 的干净方法?

java - 将文件上传到Android服务器时如何在表单数据中发送多个参数?