startForeground 通知未显示标题或内容。

5

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

它能够正常工作,但是通知中未显示我的标题或内容(通知提示为"xxx正在运行",点击以获取更多信息或停止应用程序)。现在主要针对Android 10进行开发。

该服务是从我的主Activity中启动的。

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

在Service的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

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

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

你需要在 Android O 以上版本中创建通知渠道。请参考这个链接 - Ryosuke
谢谢您的回复。我已经看到了编辑。 - Alexander Jäger
2个回答

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

当我尝试使用NotificationManager.notify手动显示通知时,我发现了这个问题。


0
看起来你的代码是有效的。
你需要在AndroidManifest.xml中添加<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />来在你的设备上显示应用程序的闹钟。 (即使没有SecurityException这样的东西。)
然后打开你的应用程序闹钟。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接