通知未在三星Oreo设备中显示

时间:2019-03-07 08:25:34

标签: android push-notification notification-channel

我今天遇到一个奇怪的问题,推送通知未在其中装有奥利奥的三星设备中显示,但在其他奥利奥设备中运行正常。这是我正在使用的代码:

 private void sendNotification(String messageTitle,String messageBody) {

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder notificationBuilder=null;
        try {
        Intent intent = new Intent(this, SplashActivity.class);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        String NOTIFICATION_CHANNEL="NB Shop Notification";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.icon)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                .setSound(defaultSoundUri)
                .setChannelId(NOTIFICATION_CHANNEL)
                .setContentIntent(pendingIntent);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            /* Create or update. */
            NotificationChannel channel;
            channel=new NotificationChannel(NOTIFICATION_CHANNEL,
                    NOTIFICATION_CHANNEL,
                    NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
            notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
        }catch (Exception e)
        {
            Log.d("sendNotification",e.toString());
        }
    }

它在日志中没有显示任何错误。

1 个答案:

答案 0 :(得分:1)

我发现了引起问题的问题,不建议使用仅具有单个参数的NotificationCompat.Builder的构造函数(NotificationCompat.Builder(this)), 为了摆脱弃用,我们必须将通道ID与构造函数一起发送,因此我更改了代码并将通道ID传递给构造函数,如下所示:

NotificationCompat.Builder(this,NOTIFICATION_CHANNEL)

也已删除

.setChannelId(NOTIFICATION_CHANNEL)

现在此代码也可在三星设备上使用。