Невозможно включить мигающий свет и отключить звук уведомлений для уведомлений Oreo - PullRequest
0 голосов
/ 08 мая 2018

Я работаю с AlarmManager, и при запуске будильника также отображаются уведомления. Я создал уведомления для Oreo и для до Oreo. Уведомления до того, как Oreo работают должным образом - я могу отключить звуки и установить освещение, но я не могу заставить это работать в Oreo. У меня была похожая проблема с вибрациями, но я смог найти рабочее решение. Я пробовал много вещей ( 1 , 2 , 3 , 4 , 5 , 6 ...), от NotificationCompat до изменения важности, но не смог заставить его работать.

Моя проблема связана только с уведомлениями Oreo, я не могу отключить звук (он срабатывает каждый раз), и я не могу заставить мигать свет. Я прошел через кучу вопросов SO и официальную документацию. Некоторые решения устарели, устарели (NotificationCompat.Builder), другие не работают вообще (включая некоторые примеры из официальной документации).

Вот мой код для Oreo (не работает) и для более старых (работает) :

//region Oreo notifications
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    CharSequence name = "AlarmNotification";
    String description = "Alarm notification";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;

    NotificationChannel mChannel = new NotificationChannel(channelIdOreo, name, importance);
    mChannel.setDescription(description);
    mChannel.setShowBadge(true);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.RED);

    if (notificationManager != null) {
        notificationManager.createNotificationChannel(mChannel);
    }

    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

    if (sNotifications.equals("false")) {
        //NOT WORKING
        mChannel.setSound(null, null);
    }
    //VIBRATION WORKING
    if (sVibration.equals("true")) {
        if (vibrator != null && vibrator.hasVibrator()) {
            VibrationEffect effect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);
            vibrator.vibrate(effect);
        }
    }

    Notification notification = new Notification.Builder(context, channelIdOreo)
            .setContentTitle(contentTitleText)
            .setContentText(contentContentText)
            .setNumber(1)
            .setSmallIcon(whiteLogo)
            .setBadgeIconType(whiteLogo)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build();

    if (notificationManager != null) {
        notificationManager.notify(notificationCode, notification);
    }
}
//endregion

//region Pre-Oreo notifications
else {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(whiteLogo)
            .setLargeIcon(largeIcon)
            .setContentTitle(contentTitleText)
            .setContentText(contentContentText)
            .setOngoing(false)
            .setNumber(1)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true);

    mBuilder.setLights(colorPPDOrange, 1000, 2000);

    if (sNotifications.equals("true")) {
        mBuilder.setSound(uri);
    }
    if (sVibration.equals("true")) {
        mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
    }
    mBuilder.setContentIntent(pendingIntent);
    if (notificationManager != null) {
        notificationManager.notify(notificationCode, mBuilder.build());
    }
}
//endregion

1 Ответ

0 голосов
/ 07 августа 2018

Наконец-то нашел ответ. Каждый раз, когда я изменял что-либо, связанное с моим каналом, мне приходилось менять свой идентификатор канала на совершенно новый идентификатор, который никогда не использовался до до . Он не может просто отличаться от текущего идентификатора . Кроме этого я заменил мой строковый ресурс на фактическую строку в коде. Также мне пришлось переместить несколько строк кода, как показано ниже.

Вот так выглядит мой код:

String channelIdOreo = "FfffffF";

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    //region Oreo otification
    Notification notification = new Notification.Builder(context, channelIdOreo)
            .setContentTitle(contentTitleText)
            .setContentText(contentContentText)
            .setNumber(1)
            .setSmallIcon(whiteLogo)
            .setBadgeIconType(whiteLogo)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build();
    //endregion

    NotificationChannel mChannel = new NotificationChannel(channelIdOreo, "Channel human readable title and stuff", NotificationManager.IMPORTANCE_DEFAULT);

    mChannel.enableLights(true);
    mChannel.setLightColor(Color.YELLOW);

    //region Conditions from settings
    if (sNotifications.equals("true")) {
        mChannel.setSound(uri, null);
    } else {
        mChannel.setSound(null, null);
    }

    if (sVibration.equals("true")) {
        mChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});
    } else {
        mChannel.enableVibration(false);
    }
    //endregion

    if (notificationManager != null) {
        notificationManager.createNotificationChannel(mChannel);
    }
    if (notificationManager != null) {
        notificationManager.notify(notificationCode, notification);
    }
}

Надеюсь, это сэкономит кому-то время.

...