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

问题描述 投票:0回答:1

尝试按照代码启动前台服务:

final Notification.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  final NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    getApplicationContext().getPackageName(), NotificationManager.IMPORTANCE_HIGH);
  mNotificationManager.createNotificationChannel(channel);
  notificationBuilder = new Notification.Builder(mAppContext, CHANNEL_ID);
} else {
  notificationBuilder = new Notification.Builder(mAppContext);
}
final Notification notification = notificationBuilder
            .setContentTitle(mAppContext.getResources()
            .getString(R.string.initiate_partner_apps))
            .setSmallIcon(R.drawable.ic_launcher)
            .build();
startForeground(NOTIFICATION_ID, notification);

但是我面临以下错误:

D AndroidRuntime: Shutting down VM
E AndroidRuntime: FATAL EXCEPTION: main
E AndroidRuntime: Process: com.my.package, PID: 8320
E AndroidRuntime: android.app.RemoteServiceException: Bad notification for startForeground
E AndroidRuntime:   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2020)
E AndroidRuntime:   at android.os.Handler.dispatchMessage(Handler.java:106)
E AndroidRuntime:   at android.os.Looper.loop(Looper.java:223)
E AndroidRuntime:   at android.app.ActivityThread.main(ActivityThread.java:7719)
E AndroidRuntime:   at java.lang.reflect.Method.invoke(Native Method)
E AndroidRuntime:   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E AndroidRuntime:   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

上述代码在 Android 8.1 中不会导致任何问题,但仅在 Android 11 中开始出现此问题。

到目前为止,无论我在网上看到什么,错误消息还列出了指出无效频道 ID 的原因。就我而言,不仅没有列出任何原因,而且我一直在使用相同的常数

CHANNEL_ID
,所以我知道我没有犯这个错误。

我无法理解此错误的可能原因是什么

java android service notifications android-notifications
1个回答
1
投票

真正想要开始什么?前台服务或通知(或两者)? 如果是前台服务,您可以有意地执行此操作(而不是通知): Intent serviceIntent = new Intent(this, ForegroundService.class); startForegroundService(serviceIntent);

如果您想显示通知,则该行

notificationManager.notify(NOTIFICATION_ID, notification);

不见了。

© www.soinside.com 2019 - 2024. All rights reserved.