«Плохое уведомление для startForeground: Неверный канал для сервисного уведомления», даже если канал был установлен - PullRequest
0 голосов
/ 04 июня 2019

Каковы могут быть другие возможные причины

Fatal Exception: android.app.RemoteServiceException
Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification

помимо отсутствия набора каналов?Кажется, это происходит только на Android 8 и 9

Моя трассировка стека показывает, что канал имеет значение:

invalid channel for service notification: Notification(channel=com.myapp.notifications pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x52 color=0x00000000 category=service number=0 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)

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

Мой фоновый сервис настроен на обычное

    public static final String NOTIFICATION_CHANNEL_ID = "com.myapp.notifications";
    public static final String SERVICE_CHANNEL_ID = "com.myapp.services";
    public static final int NOTIFICATION_ID = 100;

    @Override
    public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(2, buildNotification(getApplicationContext()));
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    Notification buildNotification(Context context) {
        String channelId = SERVICE_CHANNEL_ID;
        setupNotificationChannel(context, channelId);

        return NotificationCompat.Builder(context, channelId)
                .setOngoing(true)
                .setSmallIcon(R.drawable.app_icon)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setAutoCancel(true)
                .setChannelId(channelId)
                .build();
    }

    @RequiresApi(Build.VERSION_CODES.O)
    void setupNotificationChannel(Context context, String channelId) {
        NotificationManager notificationManager = getNotificationManager(context);

        if (notificationManager.getNotificationChannel(channelId) == null) {
            NotificationChannel channel = NotificationChannel(channelId, getChannelName(channelId), getChannelImportance())
            channel.setDescription(getChannelDescription(channelId))
            notificationManager.createNotificationChannel(channel)
        }
    }

Я также отображаю некоторые push-уведомления аналогичным образом:

    public void showNotification(Context context) {
        NotificationManager notificationManager = getNotificationManager(context);

        String channelId = SHRNotificationService.NOTIFICATION_CHANNEL_ID;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setupNotificationChannel(context, channelId);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setContentTitle(getNotificationTitle())
                .setColor(ContextCompat.getColor(context, R.color.BLUE))
                .setChannelId(channelId)
                .setPriority(getNotificationPriority(channelId))
                .setAutoCancel(false)
                .setOngoing(true)
                .setOnlyAlertOnce(true);

        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

У меня есть

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

в манифесте.

Что также неясно, так это то, что трассировка стека относится к уведомлению из категории service , с com.myapp.notifications в качестве идентификатора канала,но ни одна из фоновых служб или уведомлений не удовлетворяет обоим этим условиям.

1 Ответ

0 голосов
/ 04 июня 2019

Это было давно, но я думаю, вот как ты хочешь, чтобы это выглядело:

     fun sendToForegroundWithNotification() {
        val CHANNEL_ID = "YourChannelId"

        @Suppress("DEPRECATION") //for the NotificationBuilder < API26 ctor
        val notificationBuilder: Notification.Builder
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // O > need a channel, create one
            notificationManager.createNotificationChannel(
                    NotificationChannel(
                            CHANNEL_ID,
                            "Title",
                            NotificationManager.IMPORTANCE_DEFAULT
                    )
            )
            notificationBuilder = Notification.Builder(this, CHANNEL_ID)
        } else notificationBuilder = Notification.Builder(this)


        val notification = notificationBuilder
                .setContentTitle(getText(R.string.app_name))
                .setContentText(getText(R.string.your_content))
                .setSmallIcon(R.drawable.some_icon)
                .etc(whatever you need)
                .build()


        // since you're in your Service, you can call startFg directly:
        startForeground(666, notification) // ;-)

     }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...