0

I use this code to show notifications users of my app.

On some devices, this code works perfectly, but some devices do not show a notification at all.

Is someone know what is the problem?

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

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
kingHY
  • 11
  • 1

1 Answers1

0

You need to add a notification channel for API 26 and above, like this:

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();
    }
deluxe1
  • 737
  • 4
  • 15