Я получаю это сообщение при попытке отобразить уведомление на Android O.
Использование типов потоков устарело для операций, отличных от томов Контроль
Уведомление прямо из примера docs и отлично отображается на Android 25.
Я получаю это сообщение при попытке отобразить уведомление на Android O.
Использование типов потоков устарело для операций, отличных от томов Контроль
Уведомление прямо из примера docs и отлично отображается на Android 25.
В комментариях к этой странице в Google+:
те [предупреждения] в настоящее время ожидаются при использовании
NotificationCompat
на устройствах Android O (NotificationCompat
всегда вызываетsetSound()
, даже если вы никогда не проходите в пользовательском звуке).пока Библиотека поддержки не изменит свой код, чтобы использовать
AudioAttributes
версиюsetSound
, вы всегда получите это предупреждение.
Поэтому вы ничего не можете сделать об этом предупреждении. Согласно руководству
Начиная с Android O, вам необходимо настроить NotificationChannel и указать этот канал при попытке отобразить уведомление.
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
...
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setVibrate(new long[]{0, 100, 100, 100, 100, 100})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Content Title")
.setContentText("Content Text");
notificationManager.notify(NOTIFICATION_ID, builder.build());
Несколько важных заметок:
NotificationChannel
, переопределяют те, которые указаны в фактическом Notification
. Я знаю, его контр-интуитивный. Вы должны либо переместить параметры, которые будут меняться, либо использовать другой NotificationChannel для каждой конфигурации.NotificationChannel
после того, как вы передали его на createNotificationChannel()
. Вы даже не можете позвонить deleteNotificationChannel()
, а затем попытаться повторно добавить его. Использование идентификатора удаляемого NotificationChannel
приведет к его воскрешению, и оно будет таким же неизменным, как и при его создании. Он будет продолжать использовать старые настройки, пока приложение не будет удалено. Поэтому вам лучше быть уверенными в настройках вашего канала и переустанавливать приложение, если вы играете с этими настройками, чтобы они вступили в силу.Все, что @sky-kelsey описал хорошо, просто незначительные дополнения:
Вы не должны регистрировать один и тот же канал каждый раз, если он уже зарегистрирован, поэтому у меня есть метод класса Utils, который создает для меня канал:
public static final String NOTIFICATION_CHANNEL_ID_LOCATION = "notification_channel_location";
public static void registerLocationNotifChnnl(Context context) {
if (Build.VERSION.SDK_INT >= 26) {
NotificationManager mngr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
if (mngr.getNotificationChannel(NOTIFICATION_CHANNEL_ID_LOCATION) != null) {
return;
}
//
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID_LOCATION,
context.getString(R.string.notification_chnnl_location),
NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel.
channel.setDescription(context.getString(R.string.notification_chnnl_location_descr));
channel.enableLights(false);
channel.enableVibration(false);
mngr.createNotificationChannel(channel);
}
}
strings.xml:
<string name="notification_chnnl_location">Location polling</string>
<string name="notification_chnnl_location_descr">You will see notifications on this channel ONLY during location polling</string>
И я вызываю метод каждый раз, прежде чем я покажу уведомление о типе:
...
NotificationUtil.registerLocationNotifChnnl(this);
return new NotificationCompat.Builder(this, NotificationUtil.NOTIFICATION_CHANNEL_ID_LOCATION)
.addAction(R.mipmap.ic_launcher, getString(R.string.open_app),
activityPendingIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.remove_location_updates),
servicePendingIntent)
.setContentText(text)
...
Еще одна типичная проблема - звук по умолчанию канала - здесь: fooobar.com/questions/252570/...
В Android O не рекомендуется использовать NotificationChannel
и NotificationCompat.Builder
(reference).
Ниже приведен пример кода:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());