Android通知:打开应用程序时不显示通知吗? [英] Notification Android : Don't show notification when app is open?

查看:148
本文介绍了Android通知:打开应用程序时不显示通知吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目上,并且我将Intent Service与wakefulBroadcastReceiver一起使用来安排警报并发送通知.到目前为止没有任何问题.但是我想在打开应用程序时不再显示通知.对这个问题有任何想法吗?.

I'm working on a project and I use Intent Service with wakefulBroadcastReceiver to schedule alarm and send notification. There are no problems this far. But I want when I open my app, it don't displaying notification again. Please any idea for this problem?.

推荐答案

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

In your notification receiver when you receive the notification you can check whether the app is in background or not and take a decision of showing the notification accordingly.

这里是检查应用程序是否在后台的代码.

Here's a code to check whether the app is in background or not.

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

这篇关于Android通知:打开应用程序时不显示通知吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆