0

我使用此代码向我的应用程序的用户显示通知。

在某些设备上,此代码可以完美运行,但某些设备根本不显示通知。

有人知道是什么问题吗?

private void sendNotification(String title, String messageBody, Map<String, String> allData) {
    Intent intent = new Intent(this, ReferralPage.class);
    intent.putExtra("title", title);
    intent.putExtra("text", messageBody);

    String tid = allData.get("tid");
    intent.putExtra("tid", tid);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_"+tid)
            .setSmallIcon(com.escodes.R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_MAX);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    long time = new Date().getTime();
    String tmpStr = String.valueOf(time);
    String last4Str = tmpStr.substring(tmpStr.length() - 5);
    int notificationId = Integer.valueOf(last4Str);
    notificationManager.notify(notificationId, notificationBuilder.build());

}
4

1 回答 1

0

您需要为 API 26 及更高版本添加通知通道,如下所示:

if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "ID_OF_THE_CHANNEL";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "name_of_the_channel",
                NotificationManager.IMPORTANCE_DEFAULT);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
        Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setContentTitle("title")
                .setContentText("text")
                ...
                ...
                .build();
    }
于 2018-10-30T12:09:53.067 回答