java - startForeground 通知不显示标题或内容

标签 java android flutter kotlin

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

它工作正常,但是,通知没有显示我的标题或内容(它说“xxx is running”点击获取更多信息或停止应用程序)。我现在的目标是 Android 10

服务是从我的主要 Activity 开始的

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

在服务的 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);

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

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

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

最佳答案

我发现了问题:

您需要设置一个有效的小图标。否则通知显示将在 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()

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

关于java - startForeground 通知不显示标题或内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61738137/

相关文章:

android - 如何为 MPAndroidChart BarChart 设置高度和宽度?

flutter - 难以在我的 flutter 应用程序的各个屏幕中导航

flutter - 如何在本地运行 flutter web build

android - 一种在 flutter 中将最小化的应用程序置于前台的方法

c# - System.convert.ToString() 与 C# 中的显式类型转换

java - 如何在 JavaFX 中将 CheckBox 添加到 TableView

java - ant "<input addproperty=..."无法在 Linux 中的 bash 中工作

java - 所拍摄照片的亮度问题 (Xamarin.Android)

android - Firebase 条件列表数据检索 android

Java Swing 计算器