Android 遇到:android.app.RemoteServiceException$CannotPostForegroundServiceNotificationException: Bad notification for startForeground : 如何解决:
原因:API版本大于18,直接使用 new Notification() 来创建前台服务的通知仍然是不被接受的,因为这没有提供必要的通知细节(如图标、标题),违反了Android对于前台服务通知的规定。从Android 8.0(API 26)开始,还需要通过通知渠道发送通知。
针对您的代码,应该进行如下修改:
创建通知渠道(针对API 26及以上)。
构建一个完整的通知,包含必要的元素(小图标、标题、内容)。
解决方案:在对应使用Notification 的服务中修改
@Override
public void onCreate() {
Log.i(TAG, “CoreInnerService -> onCreate”);
super.onCreate();
// 创建通知渠道,针对Android 8.0及以上版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"VM Daemon Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "CoreInnerService -> onStartCommand");
// startForeground(CORE_SERVICE_ID, new Notification());
//确保服务运行在前台
Notification notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("交通安全管控正在运行")
.setContentText("正在运行")
.setSmallIcon(R.drawable.ic_launcher) // 设置图标,需替换为实际资源ID
.build();
startForeground(CORE_SERVICE_ID, notification);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}