notification does not appear?

Refresh

March 2019

Views

50 time

1

Here is my notification builder func:

public class NotificationHelper {

final static String CHANNEL_ID = "MY_CHANNEL_ID";
final static String CHANNEL_NAME = "MY_CHANNEL_NAME";


public static Notification buildNotificationInstance(Context ctx, String title, String message) {

    Notification notification;
    NotificationCompat.Builder mBuilder;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        mBuilder = new NotificationCompat.Builder(ctx, CHANNEL_ID);
    } else {
        mBuilder = new NotificationCompat.Builder(ctx);
    }

    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_android_black_24dp);

    Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher);
    mBuilder.setLargeIcon(bm);


    notification = mBuilder.build();


    return notification;
    }
}

And I try to show the notification on Activity's onCreate():

Notification notification = NotificationHelper.buildNotificationInstance(this, "title", "message");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

The notification doesn't show. What am I doing wrong?

I test on Android 8

2 answers

1

you must add pendingIntent for notificationBuilder as well , like this :

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

mBuilder.setContentTitle(title)
        .setContentText(message)
        .setSmallIcon(R.drawable.ic_android_black_24dp)
        .setContentIntent(pendingIntent);
1

Вы должны создать канал уведомления для его работы: Попробуйте это:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        mBuilder = new NotificationCompat.Builder(ctx, CHANNEL_ID);

        notificationChannel.setDescription("description");
        notificationChannel.enableLights(true);
        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }