From the developer documentation:
When you target Android 8.0 (API level 26), you must implement one or more notification channels to display notifications to your users.
int NOTIFICATION_ID = 234;
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
CharSequence name = "my_channel";
String Description = "This is my channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setDescription(Description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message);
Intent resultIntent = new Intent(ctx, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
One interesting thing to note: If a channel already exists, calling createNotificationChannel
has no effect, so you can create all channels whenever you start your application.