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