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
Here is an alternative solution that uses reflection to create the Notification Channel so you can set a compileSdkVersion
of lower than 26.
private void createNotificationChannel(NotificationManager notificationManager) {
// Channel details
String channelId = "myChannelId";
String channelName = "Notifications";
// Channel importance (3 means default importance)
int channelImportance = 3;
try {
// Get NotificationChannel class via reflection (only available on devices running Android O or newer)
Class notificationChannelClass = Class.forName("android.app.NotificationChannel");
// Get NotificationChannel constructor
Constructor> notificationChannelConstructor = notificationChannelClass.getDeclaredConstructor(String.class, CharSequence.class, int.class);
// Instantiate new notification channel
Object notificationChannel = notificationChannelConstructor.newInstance(channelId, channelName, channelImportance);
// Get notification channel creation method via reflection
Method createNotificationChannelMethod = notificationManager.getClass().getDeclaredMethod("createNotificationChannel", notificationChannelClass);
// Invoke method on NotificationManager, passing in the channel object
createNotificationChannelMethod.invoke(notificationManager, notificationChannel);
// Log success to console
Log.d("MyApp", "Notification channel created successfully");
}
catch (Exception exc) {
// Log exception to console
Log.e("MyApp", "Creating notification channel failed", exc);
}
}
Then, when you're building your notifications, simply call the .setChannelId()
method of NotificationCompat.Builder
:
builder.setChannelId("myChannelId");
Note: You need to update your appcompat-v7
library to version 26.x.x
in build.gradle
:
compile 'com.android.support:appcompat-v7:26.1.0'