startForeground 通知不显示标题或内容

Ale*_*ger 5 java android kotlin flutter

我正在启动一个前台服务,它使用 HandlerThread 来执行一些长时间运行的任务。

它工作正常,但是,通知不显示我的标题或内容(它说“xxx正在运行”,点击了解更多信息或停止应用程序”)。我现在的目标是Android 10

该服务从我的主要活动开始

Log.w(TAG, "startServiceCalled")
Intent(this, MyService::class.java).also { intent ->
    startForegroundService(intent)
}
Run Code Online (Sandbox Code Playgroud)

onCreate服务的回调中,我将服务放在前台,如下所示

val pendingIntent: PendingIntent =
    Intent(this, MainActivity::class.java).let { notificationIntent ->
    PendingIntent.getActivity(this, 0, notificationIntent, 0)
}

val notification: Notification = NotificationCompat.Builder(applicationContext, MainActivity.RECORDING_NOTIFICATION_CHANNEL.id)
    .setOngoing(true)
    .setContentTitle("My Custom App")
    .setContentText("MyService Ready")
    .setContentIntent(pendingIntent)
    .build()

startForeground(NOTIFICATIION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST);
Run Code Online (Sandbox Code Playgroud)

顺便说一句:我也在使用 Flutter,所以我的主要活动扩展了 FlutterActivity

编辑:通知通道是这样创建的

val RECORDING_NOTIFICATION_CHANNEL = NotificationChannel("com.example.notification", "Service notifications", NotificationManager.IMPORTANCE_DEFAULT).apply {
    description = "Provides information about the service"
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(RECORDING_NOTIFICATION_CHANNEL);
Run Code Online (Sandbox Code Playgroud)

Ale*_*ger 13

我发现了这个问题:

您需要设置一个有效的小图标。否则,通知显示将在 startForeground 期间静默失败。

val notification: Notification = NotificationCompat.Builder(applicationContext, MainActivity.RECORDING_NOTIFICATION_CHANNEL.id)
        .setOngoing(true)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("MyService")
        .setContentText("Recording Service Ready")
        .setContentIntent(pendingIntent)
        .build()
Run Code Online (Sandbox Code Playgroud)

我在尝试使用NotificationManager.notify手动显示通知时发现了这一点。