NotificationCompat与API 26

tyc*_*czj 56 android android-notifications

我没有看到任何有关如何使用NotificationCompat与Android O的信息 Notification Channels

我确实看到一个新的构造函数,它接受一个channelId但是如何获取Compat通知并在NotificationChannel中使用它,因为createNotificationChannel它需要一个NotificationChannel对象

sta*_*ken 127

NotificationChannel如果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);
}
Run Code Online (Sandbox Code Playgroud)

然后使用:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default");
Run Code Online (Sandbox Code Playgroud)

因此,您的通知适用于API 26(带通道)和下面(无).

  • 是需要一次创建频道,还是每次都需要创建? (2认同)

Rag*_*a M 15

声明通知管理器:

   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";
Run Code Online (Sandbox Code Playgroud)

通知频道

    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";
Run Code Online (Sandbox Code Playgroud)

通知生成器

        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();
Run Code Online (Sandbox Code Playgroud)

NotificationManager通知用户:

            mNotific.notify(ncode, n);
Run Code Online (Sandbox Code Playgroud)