Не удалось опубликовать уведомление на канале" null " целевой Api-26

два журнала показывает

1: использование типов потоков не рекомендуется для операций, отличных от регулятора громкости

2: см. документацию setSound () для того, что использовать вместо android.сми.AudioAttributes, чтобы претендовать ваше использование воспроизведение делу

Showing this

6 ответов


когда вы нацелены на Android 8.0 (уровень API 26), Вы должны реализовать один или несколько каналов уведомлений для отображения уведомлений пользователям.

int NOTIFICATION_ID = 234;

    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);


    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {


        String CHANNEL_ID = "my_channel_01";
        CharSequence name = "my_channel";
        String Description = "This is my channel";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mChannel.setDescription(Description);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.RED);
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        mChannel.setShowBadge(false);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(message);

    Intent resultIntent = new Intent(ctx, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(resultPendingIntent);

    notificationManager.notify(NOTIFICATION_ID, builder.build());

ответ Gulzar Bhat работает отлично, если ваш минимальный API-это Oreo. Если ваш минимум ниже, однако, вы должны обернуть код NotificationChannel в проверку уровня платформы. После этого вы все равно можете использовать id, который будет проигнорирован pre Oreo:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    int importance = NotificationManager.IMPORTANCE_LOW;
    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.enableVibration(true);
    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
    notificationManager.createNotificationChannel(notificationChannel);
}

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)(System.currentTimeMillis()/1000), mBuilder.build());

сначала создайте канал уведомлений:

public static final String NOTIFICATION_CHANNEL_ID = "4655";
//Notification Channel
        CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});


NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);

затем используйте идентификатор канала в конструкторе:

final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_timers)
                .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                .setSound(null)
                .setContent(contentView)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setLargeIcon(picture)
                .setTicker(sTimer)
                .setContentIntent(timerListIntent)
                .setAutoCancel(false);

вы можете решить это двумя способами, но для обоих из них вам нужно создать канал уведомления с определенным идентификатором канала.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "my_channel_01";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, name,importance);
mChannel.enableLights(true);
mNotificationManager.createNotificationChannel(mChannel);

Первый способ-установить канал для уведомления в конструкторе:

Notification notification = new Notification.Builder(MainActivity.this , id).setContentTitle("Title");
mNotificationManager.notify("your_notification_id", notification);

Второй способ-установить канал с помощью Notificiation.Строитель.setChannelId ()

Notification notification = new Notification.Builder(MainActivity.this).setContentTitle("Title").
setChannelId(id);
mNotificationManager.notify("your_notification_id", notification);

надеюсь, что это помогает


эта проблема связана со старой версией FCM.

обновите свою зависимость до com.google.firebase:firebase-messaging:15.0.2 или выше.

это исправит ошибку

failed to post notification on channel null

когда ваше приложение получает уведомления в фоновом режиме, потому что теперь Firebase предоставляет канал уведомлений по умолчанию с основными настройками.

но вы также можете указать канал уведомлений по умолчанию для FCM в манифесте.

<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>

узнать больше здесь


Если вы получаете эту ошибку, следует обратить внимание на 2 вещи и их порядок:

  1. NotificationChannel mChannel = new NotificationChannel(id, name, importance);
  2. builder = new NotificationCompat.Builder(this, id);

также NotificationManager notifManager и NotificationChannel mChannel создаются только один раз.

есть необходимые сеттеры для уведомления:

builder.setContentTitle() // required  
       .setSmallIcon()    // required 
       .setContentText()  // required  

см., например,на Android 8.1 API 27 уведомление не отображается.