неверный канал для сервисного уведомления: Уведомление - PullRequest
0 голосов
/ 23 октября 2019

Мой код работает нормально, пока я использую эмулятор Android для его тестирования, но как только я его собираю и пытаюсь использовать на своем мобильном телефоне, я получаю следующую ошибку:

    An uncaught Exception occurred on "main" thread.
Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=channel_01 pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)

StackTrace:
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=channel_01 pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1760)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6806)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

это мой код:

@JavaProxy('org.nativescript.nstestandroid.ForegroundService')
class ForegroundService extends android.app.Service {
    onStartCommand(intent, flags, startId) {
        console.log('onStartCommand');
        super.onStartCommand(intent, flags, startId);
        return android.app.Service.START_STICKY;
    }

    onCreate() {
        console.log('onCreate')
        super.onCreate();
        this.startForeground(1, this.getNotification());
    }



 private getNotification() {
        const channel = new android.app.NotificationChannel(
            'channel_01',
            'ForegroundService Channel', 
            android.app.NotificationManager.IMPORTANCE_DEFAULT
        );
       // <const notificationManager = this.getSystemService(android.content.Context.NOTIFICATION_SERVICE) as android.app.NotificationManager;
        //notificationManager.createNotificationChannel(channel);
        const builder = new android.app.Notification.Builder(this.getApplicationContext(), 'channel_01');

        return builder.build();
    }

1 Ответ

1 голос
/ 23 октября 2019

Вам необходимо создать NotificationChannel перед тем, как разместить в нем новый Notification. Что-то вроде этого:

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

    // Don't see these lines in your code...
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

вы только создаете новый канал (как объект), но никогда не вызываете createNotificationChannel

, вы, вероятно, создали канал уведомлений на эмуляторе, но не на устройстве. также существует вероятность того, что некоторые устройства с более ранними версиями ОС могут автоматически создавать канал уведомлений «по умолчанию» в целях совместимости, но для более новых версий ОС может потребоваться создание канала перед отображением уведомления

в некоторых руководствах по ЗДЕСЬ

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