Подтвердить что ты не робот

NotificationCompat.Builder устарел в Android O

После обновления моего проекта до Android O

buildToolsVersion "26.0.1"

Lint в Android Studio показывает устаревшее предупреждение для следующего метода построения уведомлений:

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?

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

new Notification.Builder(MainActivity.this, "channel_id")
4b9b3361

Ответ 1

В документации упоминается, что метод строителя NotificationCompat.Builder(Context context) устарел. И мы должны использовать конструктор с параметром channelId:

NotificationCompat.Builder(Context context, String channelId)

https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

Этот конструктор устарел на уровне API 26.0.0-beta1. использование NotificationCompat.Builder(Context, String). Все опубликованные Уведомления должны указывать идентификатор NotificationChannel.

https://developer.android.com/reference/android/app/Notification.Builder.html

Этот конструктор устарел в API уровня 26. use Notification.Builder(Context, String). Все опубликованные Уведомления должны указывать идентификатор NotificationChannel.

Если вы хотите повторно использовать компоновщики компоновщика, вы можете создать строитель с помощью channelId и передать этот конструктор вспомогательному методу и задать свои предпочтительные параметры в этом методе.

Ответ 2

enter image description here

Вот рабочий код для всех версий Android с API LEVEL 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());

UPDATE для 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());

Ответ 3

Вызвать конструктор 2-arg: Для совместимости с Android O, поддерживайте поддержку-v4 NotificationCompat.Builder(Context context, String channelId). При запуске на Android N или более ранних версиях, channelId будет проигнорирован. При работе на Android O также создайте NotificationChannel с тем же channelId.

Исходный пример кода: Пример кода на нескольких страницах JavaDoc, таких как Notification.Builder, вызывающий new Notification.Builder(mContext) устарел.

Устаревшие конструкторы: Notification.Builder(Context context) и v4 NotificationCompat.Builder(Context context) устарели в пользу Notification[Compat].Builder(Context context, String channelId). (См. Notification.Builder(android.content.Context) и v4 NotificationCompat.Builder(контекст контекста).)

Устаревший класс: Весь класс v7 NotificationCompat.Builder устарел. (См. v7 NotificationCompat.Builder.) Ранее для поддержки NotificationCompat.MediaStyle требуется v7 NotificationCompat.Builder. В Android O есть v4 NotificationCompat.MediaStyle в медиа-совместимой библиотеке android.support.v4.media. Используйте это, если вам нужно MediaStyle.

API 14 +: В библиотеке поддержки с 26.0.0 и выше пакеты поддержки-v4 и поддержки-v7 поддерживают минимальный уровень API 14. Имена v # являются историческими.

См. Недавние версии библиотеки поддержки.

Ответ 4

Вместо того, чтобы проверять Build.VERSION.SDK_INT >= Build.VERSION_CODES.O как и многие ответы, есть несколько более простой способ -

Добавьте следующую строку в раздел application файла AndroidManifest.xml, как описано в приложении " Настройка приложения Firewall Cloud Messaging Client" на Android- документе:

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

Затем добавьте строку с именем канала в файл values /strings.xml:

<string name="default_notification_channel_id">default</string>

После этого вы сможете использовать новую версию конструктора NotificationCompat.Builder с двумя параметрами (поскольку старый конструктор с 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());
}

Ответ 5

Вот пример кода, который работает в 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());

Ответ 6

Простой пример

    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);

    }

Ответ 7

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.

Итак, логика - это тот метод, который вы объявите или инициализируете, тогда тот же метод с правой стороны будет использоваться для распределения. если в Leftside = вы будете использовать какой-то метод, то тот же метод будет использоваться в правой части = для выделения с новым.

Попробуйте этот код... Он обязательно будет работать

Ответ 8

Этот конструктор устарел на уровне API 26.1.0. вместо этого используйте NotificationCompat.Builder(Context, String). Все опубликованные уведомления должны указывать идентификатор NotificationChannel.

Ответ 9

  1. Необходимо объявить канал уведомлений с Notification_Channel_ID
  2. Создайте уведомление с этим идентификатором канала. Например,

...
 public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_ID+"_name",
                NotificationManager.IMPORTANCE_HIGH);

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

notifManager.createNotificationChannel(channel);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.ic_tracker)
                .setPriority(PRIORITY_HIGH)
                .setCategory(Notification.CATEGORY_SERVICE);

        startForeground(1, builder.build());
...