【问题标题】:Notification Android : Don't show notification when app is open?通知 Android:应用打开时不显示通知?
【发布时间】:2017-02-18 07:00:03
【问题描述】:

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

【问题讨论】:

    标签: java android android-intentservice


    【解决方案1】:

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

    这是一个检查应用程序是否在后台的代码。

    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;
            }
    }
    

    【讨论】:

    • 我在 onCreate 活动中调用 Method Above? @先生。兔子
    • 是的,调用来自活动,但将其发布在应用程序类中
    • @FinnD 您需要在接收器内部调用此方法,而不是在 onCreate 中。我已经编辑了显示 GCM 接收器示例的答案,以防您使用相同的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多