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

Уведомление об уведомлении Android O не отправлено на канал - но это

Пара вопросов по уведомлению Android O:

1) Я создал канал уведомлений (см. ниже), я вызываю конструктор с .setChannelId() (передавая имя созданного мной канала "wakey", и все же, когда я запускаю приложение, я получите сообщение о том, что я не смог отправить уведомление на канал "null". Что может быть причиной этого?

2) Я подозреваю, что ответ на # 1 можно найти в "журнале", который, по его словам, проверяется, но я проверил logcat и ничего не вижу об уведомлениях или каналах. Где журнал, на который он говорит, чтобы посмотреть?

Вот код, который я использую для создания канала:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;

NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);

notificationManager.createNotificationChannel(channel);

Здесь код для генерации уведомления:

Notification.Builder notificationBuilder;

Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);

PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);

notificationBuilder= new Notification.Builder(context)
    .setContentTitle(context.getString(R.string.app_name))
    .setContentIntent(contentIntent)
    .addAction(_toggleAction);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}

notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;

int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);

Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);

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

4b9b3361

Ответ 1

Я думаю, что я узнал пару вещей, которые все добавляют к ответу:

  • Я использовал эмулятор с изображением, которое не включало Play Store.
  • Версия Google Play Services на изображении не была последней, поэтому я должен был получить уведомление, в котором сообщалось, что мне нужно обновить. Поскольку это уведомление не было применено к каналу, оно не появилось.
  • Если я установил logcat в Android Studio на "Нет фильтров" вместо "Показать только выбранное приложение", тогда я нашел журналы, в которых указывалось, что соответствующее уведомление было уведомлением о необходимости обновления "Службы".

Итак, я изменил изображение с включенным Play Марком, и он показал уведомление правильно (возможно, канал для этого уведомления должен был быть установлен в Play Маркете?), позвольте мне обновиться до последних сервисов Google Play, и я не видел этого предупреждения с тех пор.

Итак, длинный рассказ короткий (слишком поздно) - с Android O, если вы используете Google Play Services и тестируете на эмуляторе, выберите изображение с включенным Play Store или проигнорируйте тост (удачи на этом!).

Ответ 2

Сначала создайте канал уведомлений:

 public static final String NOTIFICATION_CHANNEL_ID = "4565";
//Notification Channel
        CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});


NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);

затем используйте идентификатор канала в конструкторе:

final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_timers)
                .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                .setSound(null)
                .setChannelId(NOTIFICATION_CHANNEL_ID)
                .setContent(contentView)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setLargeIcon(picture)
                .setTicker(sTimer)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false);

Ответ 3

У меня была та же проблема, и я решил ее с помощью конструктора

new Notification.Builder(Context context, String channelId), вместо того, который устарел на уровнях API> = 26 (Android O): new NotificationCompat.Builder(Context context)

Следующий код не будет работать, если ваш конструктор notificationBuilder создан с использованием устаревшего конструктора:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}

Ответ 4

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

    Notification notification = new Notification.Builder(MainActivity.this)
              .setContentTitle("New Message")
                        .setContentText("You've received new messages.")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setChannelId(channelId)
                        .build();

не используется:

Notification notification = new NotificationCompat.Builder(MainActivity.this)
                    .setContentTitle("Some Message")
                    .setContentText("You've received new messages!")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setChannel(channelId)
                    .build();

Ответ 5

Сначала необходимо создать NotificationChannel

val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);

Это единственный способ показать уведомление для API 26 +

Ответ 6

У меня была та же проблема. Он был разрешен путем создания NotificationChannel и добавления вновь созданного канала с менеджером уведомлений.

Ответ 7

Вы должны создать канал раньше.

private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
}

public void notifyThis(String title, String message) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.green_circle)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(0, mBuilder.build());
}

Наконец, вы вызываете этот метод:

createNotificationChannel();
notifyThis("My notification", "Hello World!");

Ответ 8

1. Создайте канал уведомления, прежде чем показывать уведомление (я предпочитаю активность onCreate())

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_desc);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

2.Build и Показывать уведомление через NotificationCompact вместо Notification для поддержки версии API ниже 27. Необходимо предоставить notification_id (целочисленный идентификатор, чтобы различать различные уведомления в вас приложение)

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setContentTitle(Notification_title)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    if(notificationManager!=null)
        notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());//integer id, to distinguish between different notifications.

Ответ 9

Я также хотел бы добавить, что вы получите эту ошибку, если используете инструменты Build v26+:

app/build.grade:

compileSdkVersion 26
buildToolsVersion "26.0.2"

defaultConfig {
    targetSdkVersion 26

Переход на самую низкую версию должен работать нормально.