58

I dont see any information about how to use NotificationCompat with Android O's Notification Channels

I do see a new Constructor that takes a channelId but how to take a Compat notification and use it in a NotificationChannel since createNotificationChannel takes a NotificationChannel object

tyczj
  • 71,600
  • 54
  • 194
  • 296
  • Related post - [NotificationCompat.Builder doesn't accept 2nd argument](https://stackoverflow.com/q/50765964/465053) – RBT Sep 03 '18 at 04:44

5 Answers5

134

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

stankocken
  • 2,201
  • 4
  • 19
  • 18
  • so do you have to set the sound/lights/vibration in the channel or do you still do that in the compat builder? – tyczj Jun 13 '17 at 16:11
  • 1
    You don't have to set the sounds/lights/vibration, you CAN do it. Not sure what will happen if you have a channel with custom sounds/lights/vibration and notification custom vibration for example. With API 26, because below that the channel is just ignored – stankocken Jun 13 '17 at 20:52
  • @user5195185 Try using the android support compat 26.0.2 (`compile 'com.android.support:support-compat:26.0.2'` in build.gradle) – ntcho Sep 12 '17 at 14:00
  • @stankocken, If I use TargetSDKVersion = 26 in my build.gradle, but not creating NotificationChannel then Will my app show notifications on pre oreo devices? – Mansuu.... Sep 23 '17 at 09:21
  • 1
    @stankocken Has there been changes recently - my NotificationCompat.Builder only has setChannel, not NotificationCompat.Builder.setChannelId and no ability to pass channel id in to constructor either. I'm using support.v4. I can see channel being created in settings but setChannel doesn't seem to work as debugging complains that channel is null (so doesn't send) – Paul Hadfield Sep 23 '17 at 11:09
  • @Mansuu.... Yes it will still work on pre-oreo devices, only on Oreo and above you will have the issue – stankocken Sep 24 '17 at 15:48
  • 1
    @PaulHadfield On the documentation you still have `setChannelId` and the constructor take it as well. https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html – stankocken Sep 24 '17 at 15:49
  • 2
    Do we need to create channel for once, or we need to create it every time? – Kimi Chiu Sep 25 '17 at 07:53
  • 1
    I think you need to create it only once. But if you create it multiple times it will just override the previous, so not a big issue IMO – stankocken Sep 26 '17 at 07:44
  • we might need further update like this https://stackoverflow.com/questions/43472415/notificationcompat-builder-cannot-resolve-method-build – LOG_TAG Mar 03 '18 at 14:19
  • Thanks, this answer helps a lot – Ashwin H Mar 21 '18 at 06:03
19

Declare Notification Manager:

   final NotificationManager mNotific=            
   (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    CharSequence name="Ragav";
    String desc="this is notific";
    int imp=NotificationManager.IMPORTANCE_HIGH;
    final String ChannelID="my_channel_01";

Notification Channel

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
    {
      NotificationChannel mChannel = new NotificationChannel(ChannelID, name, 
     imp);
            mChannel.setDescription(desc);
            mChannel.setLightColor(Color.CYAN);
            mChannel.canShowBadge();
            mChannel.setShowBadge(true);
            mNotific.createNotificationChannel(mChannel);
        }

    final int ncode=101;

    String Body="This is testing notific";

Notification Builder

        Notification n= new Notification.Builder(this,ChannelID)
                .setContentTitle(getPackageName())
                .setContentText(Body)
                .setBadgeIconType(R.mipmap.ic_launcher)
                .setNumber(5)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true)
                .build();

NotificationManager notify to User:

            mNotific.notify(ncode, n);
Ragavendra M
  • 442
  • 5
  • 15
1

NotificationChannel actually groups multiple notifications into channels. It basically gives more control of the notification behavior to the user. You can read more about Notification Channel and its implementation at Working with Notification Channel | With Example

Notification Channel is only applicable for Android Oreo.

 //Notification channel should only be created for devices running Android 26
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  NotificationChannel notificationChannel = new NotificationChannel("unique_channel_id","channel_name",NotificationManager.IMPORTANCE_DEFAULT);

  //Boolean value to set if lights are enabled for Notifications from this Channel
  notificationChannel.enableLights(true);

  //Boolean value to set if vibration is enabled for Notifications from this Channel
  notificationChannel.enableVibration(true);

  //Sets the color of Notification Light
  notificationChannel.setLightColor(Color.GREEN);

  //Set the vibration pattern for notifications. Pattern is in milliseconds with the format {delay,play,sleep,play,sleep...}
  notificationChannel.setVibrationPattern(new long[]{500,500,500,500,500});

  //Sets whether notifications from these Channel should be visible on Lockscreen or not
  notificationChannel.setLockscreenVisibility( Notification.VISIBILITY_PUBLIC);
}  

Note that Channel ID passed to the constructor acts as the unique identifier for that Notification Channel. Now create the Notification as shown below

// Creating the Channel
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);

To add any Notification to this Channel just pass the Channel ID as shown below

//We pass the unique channel id as the second parameter in the constructor
NotificationCompat.Builder notificationCompatBuilder=new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);

//Title for your notification
notificationCompatBuilder.setContentTitle("This is title");

//Subtext for your notification
notificationCompatBuilder.setContentText("This is subtext");

//Small Icon for your notificatiom
notificationCompatBuilder.setSmallIcon(R.id.icon);

//Large Icon for your notification 
notificationCompatBuilder.setLargeIcon(  BitmapFactory.decodeResource(getResources(),R.id.icon));

notificationManager.notify( NOTIFICATION_ID,notificationCompatBuilder.build());
Irshad Kumail
  • 1,243
  • 11
  • 10
  • Adding channel id to builder constructor fails for me: error: constructor Builder in class Builder cannot be applied to given types; new NotificationCompat.Builder(mContext, "my_channel_01") ^ required: Context found: Context,String reason: actual and formal argument lists differ in length – mcabe Jul 28 '18 at 23:39
0

Please be careful if you did all the work and you did not get any results. On some devices, you must set the notification priority.

   final NotificationCompat.Builder mBuilder = new 
    NotificationCompat.Builder(mContext, "default")
    .setPriority(Notification.PRIORITY_MAX);
Iman Marashi
  • 5,593
  • 38
  • 51
0

I know this answer is late, but better late then never!
I have just released the notification-channel-compat library which provides Notification Channel support going back to OS 4.0. Since developers anyways have to design for Channels, they can now use the benefits of Channels for all devices, and they don't have to design separately for older devices.
The library uses the built-in channel classes for OS 8.0+ devices, and mimics it for older devices. All it takes, is using our NotificationChannelCompat, NotificationChannelGroupCompat and NotificationChannelManagerHelper classes, and adding one line of code. You can see more at github. Please test it and let me know of any issues.
Thank you,
Lionscribe

lionscribe
  • 3,413
  • 1
  • 16
  • 21