我正在启动一个前台服务,它使用 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/