NotificationCompat.Строитель устаревшими в нашем о
после обновления моего проекта до Android O
buildToolsVersion "26.0.1"
Lint в Android Studio показывает устаревшее предупреждение для метода follow notification builder:
new NotificationCompat.Builder(context)
проблема: разработчики Android обновляют свою документацию, описывающую NotificationChannel для поддержки уведомлений в Android O, и предоставить нам фрагмент, но с тем же устаревшим внимание:
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();
мой вопрос: есть ли какое-либо другое решение для создания уведомлений и по-прежнему поддерживает Android O?
решение, которое я нашел, состоит в том, чтобы передать идентификатор канала в качестве параметра в уведомлении.Строитель конструктор. Но это решение не совсем многоразовые.
new Notification.Builder(MainActivity.this, "channel_id")
8 ответов:
в документации упоминается, что метод builder
NotificationCompat.Builder(Context context)была прекращена. И мы должны использовать конструктор, который имеет
вот рабочий код для всех версий android от УРОВЕНЬ API 26+ С обратной совместимостью.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID"); notificationBuilder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_launcher) .setTicker("Hearty365") .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API .setContentTitle("Default notification") .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") .setContentInfo("Info"); NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notificationBuilder.build());обновление для API 26 для установки максимального приоритета
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "my_channel_id_01"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX); // 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 notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); notificationBuilder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_launcher) .setTicker("Hearty365") // .setPriority(Notification.PRIORITY_MAX) .setContentTitle("Default notification") .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") .setContentInfo("Info"); notificationManager.notify(/*notification id*/1, notificationBuilder.build());
вызовите конструктор 2-arg: для совместимости с Android O, позвоните в службу поддержки-v4
NotificationCompat.Builder(Context context, String channelId). При запуске на Android N или ранееchannelIdбудет проигнорировано. При запуске на Android O, также создатьNotificationChannelС таким жеchannelId.устаревший пример кода: пример кода на нескольких страницах JavaDoc, таких как уведомления.Строитель вызов
new Notification.Builder(mContext)устарело.устаревший конструкторы:
Notification.Builder(Context context)и v4NotificationCompat.Builder(Context context)являются устаревшими в пользуNotification[Compat].Builder(Context context, String channelId). (См.уведомления.Строитель(андроид.содержание.Контекст) и v4 NotificationCompat.Строитель (контекст контекст).)нерекомендуемый класс: весь класс v7
NotificationCompat.Builderустарела. (См.NotificationCompat В7.Строитель.) Ранее, В7NotificationCompat.Builderнужна была поддержкаNotificationCompat.MediaStyle. В Android O есть v4NotificationCompat.MediaStyleна библиотека media-compat ' sandroid.support.v4.mediaпакета. Используйте это, если вам нужноMediaStyle.API 14+: в библиотеке поддержки от 26.0.0 и выше пакеты support-v4 и support-v7 поддерживают минимальный уровень API 14. Имена v# являются историческими.
посмотреть Последние Версии Библиотеки Поддержки.
вместо проверки
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Oкак показывают многие ответы, есть немного более простой способ -добавить следующую строку на AndroidManifest.xml файл, как описано в настройка клиентского приложения Firebase Cloud Messaging на Android doc:
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />затем добавьте строку с именем канала в значения/строки.xml file:
<string name="default_notification_channel_id">default</string>после этого вы сможете использовать новые версии из NotificationCompat.Строитель конструктор с 2 параметрами (так как старый конструктор с 1 параметром был устаревшим в Android Oreo):
private void sendNotification(String title, String body) { Intent i = new Intent(this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0 /* Request code */, i, PendingIntent.FLAG_ONE_SHOT); Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id)) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setSound(sound) .setContentIntent(pi); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(0, builder.build()); }
вот пример кода, который работает в Android Oreo и меньше, чем Oreo.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance); notificationManager.createNotificationChannel(notificationChannel); builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId()); } else { builder = new NotificationCompat.Builder(getApplicationContext()); } builder = builder .setSmallIcon(R.drawable.ic_notification_icon) .setColor(ContextCompat.getColor(context, R.color.color)) .setContentTitle(context.getString(R.string.getTitel)) .setTicker(context.getString(R.string.text)) .setContentText(message) .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true); notificationManager.notify(requestCode, builder.build());
Простой Пример
public void showNotification (String from, String notification, Intent intent) { PendingIntent pendingIntent = PendingIntent.getActivity( context, Notification_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT ); String NOTIFICATION_CHANNEL_ID = "my_channel_id_01"; NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.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(context, NOTIFICATION_CHANNEL_ID); Notification mNotification = builder .setContentTitle(from) .setContentText(notification) // .setTicker("Hearty365") // .setContentInfo("Info") // .setPriority(Notification.PRIORITY_MAX) .setContentIntent(pendingIntent) .setAutoCancel(true) // .setDefaults(Notification.DEFAULT_ALL) // .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) .build(); notificationManager.notify(/*notification id*/Notification_ID, mNotification); }
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();правильный код будет :
Notification.Builder notification=new Notification.Builder(this)с зависимостью 26.0.1 и новыми обновленными зависимостями, такими как 28.0.0.
некоторые пользователи используют этот код в форме :
Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.Итак, логика заключается в том, какой метод вы объявите или инициализируете, тогда тот же самый methode на правой стороне будет использоваться для выделения. если в левой части = вы будете использовать какой-то метод, то тот же метод будет использоваться в правой части = для выделения с новым.
попробовать это code...It будет обязательно работать
этот конструктор был устаревшим на уровне API 26.1.0. использовать NotificationCompat.Вместо этого строитель (контекст, строка). Все опубликованные уведомления должны указывать идентификатор NotificationChannel.

Comments