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

Я получаю тост на Android 8.1 API 27:

Предупреждение разработчика для пакета "my_package_name"
Не удалось опубликовать уведомление о ...

Logcat включает следующие строки:

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

W / Notification: см. Документацию по setSound (), чтобы узнать, что использовать вместо android.media.AudioAttributes, чтобы определить вариант использования воспроизведения.

E / NotificationService: не найден канал для pkg = my_package_name

Полная информация в Toast и Logcat может помочь в локализации этой проблемы.


person Andy Sander    schedule 28.10.2017    source источник
comment
Опубликуйте код пожалуйста   -  person Samuel Robert    schedule 28.10.2017
comment
Возможный дубликат Уведомления не отображаются в Android Oreo (API 26)   -  person Sky Kelsey    schedule 15.12.2017
comment
Связанное сообщение - NotificationCompat.Builder не принимает второй аргумент   -  person RBT    schedule 03.09.2018


Ответы (4)


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

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

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

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

  • builder.setContentTitle () // обязательно
  • .setSmallIcon () // обязательно
  • .setContentText () // обязательно

См. Пример:

private NotificationManager notifManager;
public void createNotification(String aMessage, Context context) {
    final int NOTIFY_ID = 0; // ID of notification
    String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
    String title = context.getString(R.string.default_notification_channel_title); // Default Channel
    Intent intent;
    PendingIntent pendingIntent;
    NotificationCompat.Builder builder;
    if (notifManager == null) {
        notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = notifManager.getNotificationChannel(id);
        if (mChannel == null) {
            mChannel = new NotificationChannel(id, title, importance);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            notifManager.createNotificationChannel(mChannel);
        }
        builder = new NotificationCompat.Builder(context, id);
        intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentTitle(aMessage)                            // required
               .setSmallIcon(android.R.drawable.ic_popup_reminder)   // required
               .setContentText(context.getString(R.string.app_name)) // required
               .setDefaults(Notification.DEFAULT_ALL)
               .setAutoCancel(true)
               .setContentIntent(pendingIntent)
               .setTicker(aMessage)
               .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
    }
    else {
        builder = new NotificationCompat.Builder(context, id);
        intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentTitle(aMessage)                            // required
               .setSmallIcon(android.R.drawable.ic_popup_reminder)   // required
               .setContentText(context.getString(R.string.app_name)) // required
               .setDefaults(Notification.DEFAULT_ALL)
               .setAutoCancel(true)
               .setContentIntent(pendingIntent)
               .setTicker(aMessage)
               .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
               .setPriority(Notification.PRIORITY_HIGH);
    }
    Notification notification = builder.build();
    notifManager.notify(NOTIFY_ID, notification);
}
person Andy Sander    schedule 28.10.2017
comment
* Я установил идентификатор канала, но уведомление по-прежнему не отображается; * Наконец, я обнаружил, что моя проблема заключается в том, что не вызывается метод setContentText () * Мне действительно помогло то, что вы упомянули необходимые сеттеры! - person Jeffery Ma; 06.03.2018
comment
Работал. Большое спасибо :) - person Yesha; 09.10.2018
comment
После многих часов проб и ошибок, наткнулся на это и вуаля! Спасибо. - person Maurice; 22.08.2019
comment
Замечательный тут !! но чтобы он работал, я меняю NotificationComppat.Builder на Notificaction.Builder внутри if (версия SDK) - person San Juan; 19.10.2019

Ответ Энди работает, однако я хотел избежать устаревшего Builder и следовать FireBase Quickstart Project. Я только что добавил код до того, как пришло уведомление от менеджера.

String channelId = "default_channel_id";
String channelDescription = "Default Channel";
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
    if (notificationChannel == null) {
        int importance = NotificationManager.IMPORTANCE_HIGH; //Set the importance level
        notificationChannel = new NotificationChannel(channelId, channelDescription, importance);
        notificationChannel.setLightColor(Color.GREEN); //Set if it is necesssary
        notificationChannel.enableVibration(true); //Set if it is necesssary
        notificationManager.createNotificationChannel(notificationChannel);
    }
}

//notificationManager.notify as usual

Изменить: они удалили проверку существования канала из примера, я не знаю почему.

person engincancan    schedule 18.12.2017

Я установил идентификатор канала, но уведомление по-прежнему не отображается.

Наконец, я обнаружил, что моя проблема в том, что не вызывается метод setContentText ().

Мне действительно помогло то, что @Andy Sander упомянул «обязательные сеттеры»!

вот необходимые установщики для уведомлений в Android 8 Oreo API 26 и новее:

builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
.setChannelId(id) // required for deprecated in API level >= 26 constructor .Builder(this)
person Jeffery Ma    schedule 06.03.2018
comment
документация временами недостаточно конкретна. - person filthy_wizard; 07.03.2018
comment
Привет, Аллен, надеюсь, у тебя все хорошо, пожалуйста, взгляни на мой вопрос stackoverflow.com/questions/50748028/ < / а> - person Ankita Singh; 09.06.2018

Также не забудьте привязать свой channel_id к конструктору уведомлений. После привязки моя проблема исчезла.

notificationBuilder.setChannelId(channelId)

or

NotificationCompat.Builder(Context context, String channelId)
person asozcan    schedule 31.07.2018
comment
stackoverflow.com/questions/45462666/ - person Andy Sander; 02.08.2018
comment
Следует использовать только второй метод - person barnacle.m; 21.11.2018