Почему не показывает уведомление на Android 9

Не показывает уведомление на Android 9.0 и отлично работает на 8 и ниже. У меня были проблемы со старым кодом, и я прочитал, что он необходим для передачи канала в новой версии Android, я получил этот код из Интернета, но все еще не работает на Android 9.0. Я не знаю почему. Любая помощь будет оценена.

Пока читал в инете все нормально. Но уведомление не показывает.

    private void showSmallNotification( int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent){
        String CHANNEL_ID = Constants.ChannelID;
        String CHANNEL_NAME = "Notification";

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);;
        NotificationCompat.Builder notification;
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        inboxStyle.addLine(message);

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setLightColor(Color.BLUE);
            channel.enableLights(true);
            channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.notification),
                    new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build());
            channel.canShowBadge();
            notificationManager.createNotificationChannel(channel);
            notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        } else {
            notification = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);
        }
        notification
                .setVibrate(new long[]{0, 100})
                .setPriority(Notification.PRIORITY_MAX)
                .setLights(Color.BLUE, 3000, 3000)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setWhen(getTimeMilliSec(timeStamp))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setStyle(inboxStyle)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), icon))
                .setContentText(message)
                .build();

        notificationManager.notify(CHANNEL_ID, 1, notification.build());
    }



Ответы (2)


Я думаю, проблема в том, что вы не setChannelId() на notificationBuilder. (Я позволил себе переименовать notification в notificationBuilder, так как это именно так.)

Я убрал лишнюю точку с запятой в одной из строк кода.

Также обратите внимание, что canShowBadge() — это метод класса, который возвращает значение, но не устанавливает никаких настроек уведомления. Я заменил его на setShowBadge(true).

Пожалуйста, прочтите комментарии, которые я оставил во фрагменте кода, для получения дополнительной информации.

private void showSmallNotification( int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent){
        String CHANNEL_ID = Constants.ChannelID;
        String CHANNEL_NAME = "Notification";

        // I removed one of the semi-colons in the next line of code
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        inboxStyle.addLine(message);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // I would suggest that you use IMPORTANCE_DEFAULT instead of IMPORTANCE_HIGH
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setLightColor(Color.BLUE);
            channel.enableLights(true);
            channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.notification),
                    new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build());
            //channel.canShowBadge();
            // Did you mean to set the property to enable Show Badge?
            channel.setShowBadge(true);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
            .setVibrate(new long[]{0, 100})
            .setPriority(Notification.PRIORITY_MAX)
            .setLights(Color.BLUE, 3000, 3000)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(inboxStyle)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), icon))
            .setContentText(message);
        // Removed .build() since you use it below...no need to build it twice

        // Don't forget to set the ChannelID!!
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            notificationBuilder.setChannelId(ID_SPECIAL_OFFER_NOTIFICATION);
        }

        notificationManager.notify(CHANNEL_ID, 1, notificationBuilder.build());
    }
person Barns    schedule 09.03.2019
comment
извините за поздний ответ, но все еще не показывает уведомление. - person Web.11; 20.03.2019
comment
Вы добавили setChannelId в свой код в соответствующем месте? - person Barns; 21.03.2019
comment
@ Web.11, у меня та же проблема. Как вы это решили? - person Keselme; 16.06.2019
comment
@Barns, я попробовал предложенное вами решение, могу ли я попробовать что-нибудь еще? - person Keselme; 16.06.2019
comment
@Кесельме извини. У меня нет устройства Android 9.0 для тестирования. У меня не было проблем с приведенным выше кодом на других устройствах. Удачи# - person Barns; 22.06.2019

Да, на это уже ответили, но помогите, если нужно

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int returnFlag = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("Mytrux Running")
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
            returnFlag = START_NOT_STICKY;
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("Mytrux is Running...")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
            returnFlag = START_STICKY;
        }
        mHandlerTask.run();
        return returnFlag;
    }

и добавьте этот метод также

private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    ANDROID_CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

не забудьте добавить сервис в манифест.

person CrazyMind    schedule 01.08.2019