相关疑难解决方法(0)

android.app.RemoteServiceException:startForeground 的错误通知

我正在尝试按如下方式启动前台服务:

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

    NotificationChannel chan = new NotificationChannel(
            getApplicationContext().getPackageName(),
            "My Foreground Service",
            NotificationManager.IMPORTANCE_LOW);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_SECRET);

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( 
            this, "MyChannelId");
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.my_icon)
            .setContentTitle("App is running on foreground")
            .setPriority(NotificationManager.IMPORTANCE_LOW)
            .setCategory(Notification.CATEGORY_SERVICE)
            .setChannelId("MyChannelId")
            .build();

    startForeground(1, notification);
}
Run Code Online (Sandbox Code Playgroud)

此解决方案适用于 Android 8.0 模拟器。但是我在 Android 8.1、9.0 和 10.0 模拟器上遇到以下错误。

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=MyChannelId pri=2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 …
Run Code Online (Sandbox Code Playgroud)

java service notifications android android-notifications

6
推荐指数
1
解决办法
2159
查看次数