使用API 26的NotificationCompat

58

我没有看到任何关于如何在 Android O 的 Notification Channels 中使用 NotificationCompat 的信息。

我看到了一个新的构造函数,它需要一个 channelId,但是如何将 Compat 通知转换为 NotificationChannel,因为 createNotificationChannel 需要一个 NotificationChannel 对象。


5个回答

134

仅在API >= 26时创建NotificationChannel

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

然后只需使用:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default");

所以你的通知可以在API 26(使用通道)和以下版本(不使用通道)中正常工作。


1
您不必设置声音/灯光/振动,但是可以这样做。如果您的通道具有自定义声音/灯光/振动和通知自定义振动,则不确定会发生什么。在 API 26 中,因为低于此版本的通道将被忽略。 - stankocken
1
@stankocken 最近有变化吗 - 我的 NotificationCompat.Builder 只有 setChannel,没有 NotificationCompat.Builder.setChannelId,并且构造函数中也没有传递通道 ID 的能力。我正在使用 support.v4。我可以在设置中看到通道被创建,但 setChannel 似乎不起作用,因为调试时会抱怨通道为空(因此不发送)。 - Paul Hadfield
1
@PaulHadfield 在文档中,你仍然有 setChannelId 并且构造函数也需要它。https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html - stankocken
2
我们需要只创建一次通道,还是每次都需要创建? - Kimi Chiu
1
我认为你只需要创建一次。但是如果你创建多次,它将覆盖以前的版本,所以在我看来不是一个大问题。 - stankocken
显示剩余6条评论

19

声明通知管理器:

   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";

通知渠道

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

通知管理器通知用户:

            mNotific.notify(ncode, n);

1

通知渠道实际上将多个通知分组到一起。它基本上为用户提供了更多的通知行为控制权。您可以在使用示例 | 与通知渠道一起工作中了解有关通知渠道及其实现的更多信息。

通知渠道仅适用于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);
}  

请注意,传递给构造函数的频道ID充当该通知频道的唯一标识符。现在按照以下方式创建通知。
// Creating the Channel
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);

要将任何通知添加到此频道,只需按照以下示例传递频道ID。
//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());

将频道ID添加到构建器构造函数中对我失败了:错误:无法在类Builder中应用于给定类型的构造函数Builder; new NotificationCompat.Builder(mContext, "my_channel_01") ^ 需要:上下文 找到:上下文,字符串 原因:实际参数和形式参数列表长度不同 - mcabe

0

我知道这个答案有点晚了,但迟到总比不到好!
我刚刚发布了notification-channel-compat库,它提供了通知渠道支持,适用于4.0及以上版本的操作系统。由于开发人员必须为渠道设计,因此他们现在可以为所有设备使用渠道的好处,而无需为旧设备单独设计。
该库使用OS 8.0+设备的内置渠道类,并为旧设备模拟它。只需要使用我们的NotificationChannelCompatNotificationChannelGroupCompatNotificationChannelManagerHelper类,并添加一行代码即可。您可以在github上查看更多信息。请测试它并让我知道任何issues
谢谢,
Lionscribe


0
请注意,如果您完成了所有工作但没有得到任何结果,请小心。在某些设备上,您必须设置通知的优先级
   final NotificationCompat.Builder mBuilder = new 
    NotificationCompat.Builder(mContext, "default")
    .setPriority(Notification.PRIORITY_MAX);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接