【发布时间】:2021-03-18 02:30:21
【问题描述】:
我启动一个前台服务,当用户单击按钮时下载文件。现在发生的情况是,当我再次单击该按钮时,服务内的线程第二次启动,并且我在通知中看到两个线程的进度都已更新(在线程之间跳转)。
如果第一个线程正在运行,如何防止启动第二个线程,如果服务仍在运行,如何防止调用startService() 或onStartCommand()?
class ForegroundService : Service() {
private val CHANNEL_ID = "ForegroundService Kotlin"
companion object {
fun startService(context: Context, message: String) {
val startIntent = Intent(context, ForegroundService::class.java)
startIntent.putExtra("inputExtra", message)
ContextCompat.startForegroundService(context, startIntent)
}
fun stopService(context: Context) {
val stopIntent = Intent(context, ForegroundService::class.java)
context.stopService(stopIntent)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val input = intent?.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, 0
)
//start doing some work and update the notification
//when done calling stopSelf();
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service Kotlin Example")
.setContentText(input)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder? {
return null
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
CHANNEL_ID, "Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager!!.createNotificationChannel(serviceChannel)
}
}
}
打电话
buttonGoNext.setOnClickListener {
val intent = Intent(this, DownloadActivity::class.java)
startActivity(intent)
}
【问题讨论】:
-
在本地保存通知通道id并检查是否已经有使用该id的通知运行,只需将其删除或不启动新任务
标签: android kotlin android-service