NotificationCompat with API 26

前端 未结 5 558
滥情空心
滥情空心 2020-11-27 03:38

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 cha

5条回答
  •  被撕碎了的回忆
    2020-11-27 03:59

    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());
    

提交回复
热议问题