I cannot change this feeling: again, the Android developers came up with something new and leave everybody in the dark about how they would think the feature is used.
I am talking about Notification Channels in Android O.
For years I have been using the compatibility support libraries to avoid dealing with specific platform details. Namely: NotificationCompat
.
Now, the Builder
requires me to supply a notification channel id, which is nice, but completely leaves me alone with creating such a channel. I cannot find any compat support for creating channels. Nor can I find a reasonable way to create them at the right point.
The docs simply state that it should be done "somewhere" and "probably not when issuing a notification". But what exactly am I supposed to do? I hate writing version specific stuff for simple tasks - that's why I use the compat libraries.
Does anybody have a suggestion on how to handle it? Is it "expensive" to do the creating each and every time when I want a notification to be displayed?
This is my solution to generate notifications on Android O and maintain backward compatibility:
String idChannel = "my_channel_01";
Intent mainIntent;
mainIntent = new Intent(context, LauncherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
// The id of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, null);
builder.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(getNotificationIcon())
.setContentIntent(pendingIntent)
.setContentText(context.getString(R.string.alarm_notification) + ManagementDate.getIstance().hourFormat.format(getAlarm(context, 0)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(idChannel, context.getString(R.string.app_name), importance);
// Configure the notification channel.
mChannel.setDescription(context.getString(R.string.alarm_notification));
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
} else {
builder.setContentTitle(context.getString(R.string.app_name))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(ContextCompat.getColor(context, R.color.transparent))
.setVibrate(new long[]{100, 250})
.setLights(Color.YELLOW, 500, 5000)
.setAutoCancel(true);
}
mNotificationManager.notify(1, builder.build());