我正在使用前台服务下载一个文件,但当我暂停下载时,我想停止服务,所以我做了以下操作
开业
val intent = Intent(context, IdmService::class.java)
context.startService(intent)
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
停工
context.unbindService(serviceConnection)
context.stopService(Intent(context, IdmService::class.java))
更新通知
private fun updateInfo(title: String, downloadedSize: Long, totalSize: Long) {
notification.setContentTitle(title)
notification.setContentText("${formatBytes(downloadedSize)}/${formatBytes(totalSize)}")
notification.setContentInfo(downloadSpeed)
notification.setProgress(100, progress, false)
startForeground(STICKY_NOTIFICATION_ID, notification.build())
}
但当我停止服务时,需要5秒钟才能隐藏通知。我试着评论 startForeground(STICKY_NOTIFICATION_ID, notification.build())
然后它立即隐藏通知。我想在停止服务时即时隐藏通知。我相信 startForeground
方法是异步的,这就是为什么我杀了服务后,服务在等待 startForeground
方法来完成。