首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NotificationManager时未显示通知

使用NotificationManager时未显示通知
EN

Stack Overflow用户
提问于 2020-07-12 18:01:18
回答 1查看 38关注 0票数 0

我在我的应用程序中发送推送通知,并希望即使应用程序已经在运行也能够显示它们,因此我尝试使用onMessageReceived()函数。该函数在我发送通知时运行,并且我可以看到通知的标题和正文都是正确的,所以到目前为止没有问题。然后我想在用户的设备上弹出通知,但由于某些原因,我就是不能让它工作。我看过很多网站和stackoverflow问题,所有的代码看起来基本上是一样的,所以它为什么不能在我身上工作有点令人困惑。

代码语言:javascript
复制
 @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String messageTitle = remoteMessage.getNotification().getTitle();
        String messageBody = remoteMessage.getNotification().getBody();
        System.out.println("TITLE_IS: " + messageTitle);
        System.out.println("MESSAGE_BODY: "+ messageBody);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(messageTitle)
                .setContentText(messageBody);

        //Sets ID for the notification
        int mNotificationId = (int) System.currentTimeMillis();
        

        NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(mNotificationId, mBuilder.build());

        System.out.println("Everything went fine");
    }

它从不打印最后一行(“一切都很好”),但也不会给出错误,所以即使它不能工作,它似乎也能工作。问题是什么,我该如何修复它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-13 17:45:13

最近似乎有一个更新,它需要你运行一些额外的代码,以便它在更新的android版本上工作。因此,代码应该如下所示:

代码语言:javascript
复制
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                    .setSmallIcon(R.drawable.ic_challenge)
                    .setContentTitle(messageTitle)
                    .setContentText(messageBody)
                    .setPriority(Notification.PRIORITY_MAX)
                    .setContentIntent(pendingIntent);

            //to show notification do this

            //Sets ID for the notification

            int mNotificationId = (int) System.currentTimeMillis();
            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            {
                String channelId = "Tic-Tac-Toe";
                NotificationChannel channel = new NotificationChannel(
                        channelId,
                        "Tic-Tac-Toe",
                        NotificationManager.IMPORTANCE_HIGH);
                mNotifyMgr.createNotificationChannel(channel);
                mBuilder.setChannelId(channelId);
            }

            mNotifyMgr.notify(mNotificationId, mBuilder.build());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62859647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档