NotificationCompat with API 26

Create the NotificationChannel only if API >= 26

public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default",
                                                          "Channel name",
                                                          NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    notificationManager.createNotificationChannel(channel);
}

And then just use:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default");

So your notifications are working with both API 26 (with channel) and below (without).

Leave a Comment