gpt4 book ai didi

java - android.app.RemoteServiceException : Bad notification for startForeground

转载 作者:行者123 更新时间:2023-12-02 08:31:23 30 4
gpt4 key购买 nike

我正在尝试启动前台服务,如下所示:

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

此解决方案适用于 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 category=service vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1945)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

PS:我在非模拟器 Android 9.0 设备上尝试过,没有收到此错误。

最佳答案

出现问题的原因是您正在使用 ID 创建 channel ,但使用不同的 ID 发送通知:

// Here, you are using the package name as channel ID
NotificationChannel chan = new NotificationChannel(
getApplicationContext().getPackageName(),
"My Foreground Service",
NotificationManager.IMPORTANCE_LOW);

// But here, you are sending notifications to "MyChannelId"
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
this, "MyChannelId");

因此,我相信您只需将 Channel ID 更改为 MyChannelID 即可,如下所示:

NotificationChannel chan = new NotificationChannel(
"MyChannelId",
"My Foreground Service",
NotificationManager.IMPORTANCE_LOW);

关于java - android.app.RemoteServiceException : Bad notification for startForeground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60529974/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com