Adam Varhegyi
Adam Varhegyi

Reputation: 9894

notification does not appear?

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

Upvotes: 1

Views: 75

Answers (2)

jay2109
jay2109

Reputation: 49

You have to create the notification channel for it to work: Try this:

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

Upvotes: 1

Mosa
Mosa

Reputation: 381

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

Upvotes: 1

Related Questions