0

我今天遇到了一个奇怪的问题,推送通知在装有 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());
        }
    }

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

4

1 回答 1

1

我发现了导致问题的问题,NotificationCompat.Builder(this)不推荐使用只有单个参数的 NotificationCompat.Builder 的构造函数(),为了摆脱弃用,我们必须使用构造函数发送通道 id,所以我更改了代码并将通道 id 传递给像这样的构造函数:

NotificationCompat.Builder(this,NOTIFICATION_CHANNEL)

也被删除

.setChannelId(NOTIFICATION_CHANNEL)

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

于 2019-03-07T08:30:50.903 回答