Проблема с каналом уведомлений в Android O

Я получаю тост с сообщением «Предупреждение разработчика для пакета com.google.android.apps.messaging» при отправке MMS с использованием сообщений Android версии 2.3.063.

В логах

08-12 16:57:52.368  7661  7682 W Notification: Use of stream types is deprecated for operations other than volume control
08-12 16:57:52.368  7661  7682 W Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
08-12 16:57:52.369  1604  3146 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.375  1604  3094 D CompatibilityInfo: mCompatibilityFlags - 0
08-12 16:57:52.375  1604  3094 D CompatibilityInfo: applicationDensity - 480
08-12 16:57:52.375  1604  3094 D CompatibilityInfo: applicationScale - 1.0
08-12 16:57:52.378  7661  7682 I BugleNotifications: Notifying for tag = null, type = RESIZING_NOTIFICATION_ID, notification = Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.381  7661  8893 W Notification: Use of stream types is deprecated for operations other than volume control
08-12 16:57:52.381  7661  8893 W Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
08-12 16:57:52.384  1604  1618 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.384   880  1657 W StreamHAL: Error from HAL stream in function get_presentation_position: Operation not permitted
08-12 16:57:52.387  7661  8893 I BugleNotifications: Notifying for tag = null, type = RESIZING_NOTIFICATION_ID, notification = Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.390  1604  1647 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x48 color=0xff2a56c6 vis=PRIVATE)

Сервисы Google Play версии 11.3.02
Android Messages 2.3.063
Android 8.0.0

Кто-нибудь там, чтобы помочь мне? Скриншот


person Shabbir Panjesha    schedule 14.08.2017    source источник
comment
Я прошел через это stackoverflow.com/questions/44489657/, но у меня ничего не работает   -  person Shabbir Panjesha    schedule 14.08.2017
comment
Если приложение предназначено для Android O, все уведомления должны публиковаться через [Канал уведомлений][1]. В противном случае уведомления удаляются, а всплывающее предупреждение разработчика будет отображаться на устройствах под управлением Android O. [1]: developer.android.com/preview/features/   -  person Bob    schedule 14.08.2017
comment
Но я считаю, что приложение для сообщений Android добавило бы поддержку канала уведомлений.   -  person Bob    schedule 14.08.2017
comment
Поделитесь фрагментом кода, как вы показываете уведомление.   -  person azizbekian    schedule 14.08.2017
comment
Связанный пост, если вы используете уровень API 26+ - NotificationCompat.Builder не принимает второй аргумент   -  person RBT    schedule 03.09.2018


Ответы (2)


Как написано в документации Android:

https://developer.android.com/preview/features/notification-channels.html

Если вы настроите таргетинг на Android O и опубликуете уведомление, не указав действительный канал уведомлений, уведомление не будет опубликовано, и система зарегистрирует ошибку.

Чтобы решить эту проблему, вам нужно создать NotificationChannel.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// The id of the channel.
String id = "my_channel_01";

// The user-visible name of the channel.
CharSequence name = getString(R.string.channel_name);

// The user-visible description of the channel.
String description = getString(R.string.channel_description);

int importance = NotificationManager.IMPORTANCE_LOW;

NotificationChannel mChannel = new NotificationChannel(id, name,importance);

// Configure the notification channel.
mChannel.setDescription(description);

mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);

mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

mNotificationManager.createNotificationChannel(mChannel);

А затем назначьте его своему уведомлению следующим образом:

mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

// Sets an ID for the notification, so it can be updated.
int notifyID = 1;

// The id of the channel.
String CHANNEL_ID = "my_channel_01";

// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
    .setChannelId(CHANNEL_ID)
    .build();

// Issue the notification.
mNotificationManager.notify(id, notification);

Обновление:

Если вы хотите использовать NotificationCompat, вот простой пример:

NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(getApplicationContext())
    .setSmallIcon(R.mipmap.ic_launcher_icon)
    .setContentTitle("Title")
    .setContentText("Text")
    .setOngoing(true)
    .setChannelId(id);

На самом деле вам нужно использовать Notification Builder, чтобы установить идентификатор канала через setChannelId();

person Milad Moosavi    schedule 15.08.2017
comment
что такое .setChannelId в уведомлении - person Mohit Singh; 16.08.2017
comment
Он просто привязывает канал уведомлений, который вы только что создали, к файлу notification.builder. - person Milad Moosavi; 16.08.2017
comment
я разместил свой вопрос, пожалуйста, помогите мне https://stackoverflow.com/questions/45711925/failed-to-post-notification-on-channel-null-target-api-is-26 - person Mohit Singh; 16.08.2017
comment
Где/когда я должен создать канал уведомлений? Один раз при запуске приложения? В приложении#onCreate()? - person Ridcully; 21.11.2017
comment
@Ridcully Это зависит от того, где вы делаете уведомление. Это может быть onCreate() активности или onCreateView() фрагмента. - person Milad Moosavi; 21.11.2017
comment
Вы можете создать канал один раз для каждого контекста или столько уведомлений, сколько вы пытаетесь создать. - person Milad Moosavi; 21.11.2017
comment
Сейчас я создаю канал один раз в приложении onCreate(), и он отлично работает. - person Ridcully; 21.11.2017
comment
Рад слышать. - person Milad Moosavi; 21.11.2017
comment
Спасибо @MiladMoosavi, вы спасли мой день;) - person Milad Faridnia; 19.12.2017
comment
@MiladFaridnia рад это слышать ;) - person Milad Moosavi; 19.12.2017
comment
Я получал ошибку: Wrong 1st argument type. Found: 'java.lang.String', required: 'int' в строке mNotificationManager.notify(id, notification); Итак, после передачи notifyID вместо id я теперь получаю уведомления. - person HunterrJ; 23.07.2018
comment
К вашему сведению, NotificationCompat.Builder(Context context) теперь устарело, вместо этого используйте NotificationCompat.Builder(Context context, String channelId) (и вам не понадобится .setChannelId(id)) - person cramill; 16.11.2018

Сообщения на Toast и Logcat говорят о вас, следует обратить внимание на 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 не отображать.

person Andy Sander    schedule 10.11.2017