通知未在三星奥利奥设备中显示

Notification not showing in samsung oreo devices

我今天遇到了一个奇怪的问题,推送通知在装有 oreo 的三星设备上没有显示,但在其他 oreo 设备上工作正常。这是我正在使用的代码:

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

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

我发现了导致问题的原因,NotificationCompat.Builder 的构造函数 (NotificationCompat.Builder(this)) 只有一个参数已被弃用, 为了摆脱弃用,我们必须使用构造函数发送通道 ID,所以我更改了代码并将通道 ID 传递给构造函数,如下所示:

NotificationCompat.Builder(this,NOTIFICATION_CHANNEL)

也删除了

.setChannelId(NOTIFICATION_CHANNEL)

现在这段代码也适用于三星设备。