Неверный канал для startForeground - PullRequest
0 голосов
/ 27 ноября 2018

У меня есть этот сбой в работе, который я не могу воспроизвести, и не знаю, почему это происходит.

android.app.RemoteServiceException: (Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x4a color=0x00000000 vis=PRIVATE))
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1771)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

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

Я даже не уверен, что это происходит в этой части кода, но это единственное место, где я запускаю службу переднего плана, поэтому я предполагаю, что я на правильном пути

Вот код

String channelId = NotificationChannelConstants.MAIN_NOTIFICATION_CHANNEL_ID;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelName = NotificationChannelConstants.MAIN_NOTIFICATION_CHANNEL_NAME;
    NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_LOW);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager service = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    service.createNotificationChannel(chan);
}

notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.sb_unknown)
            .setContentTitle(getString(R.string.app_name))
            .setTicker(getString(R.string.app_name)).setContentIntent(broadcastIntent)
            .setContentText(mNotificationText)
            .setAutoCancel(false)
            .setOngoing(true)
            .setOnlyAlertOnce(true);

startForeground(R.id.notification, notificationBuilder.build());

1 Ответ

0 голосов
/ 08 февраля 2019

Вы можете использовать это для версии Oreo и выше

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

@Override
public void onCreate(){
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        startMyOwnForeground();
    else
        startForeground(1, new Notification());
}

private void startMyOwnForeground(){
    String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
    String channelName = "My Background Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.icon_1)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);
} 

Конечно, не забывайте Разрешение ForeGroundService для вашего AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...