У меня есть служба, которая запускается и останавливается снова и снова, но когда она работает, она всегда должна работать как foregroundservice.
Моя текущая реализация выглядит так:
class MyService : Service() {
private val binder = LocalBinder()
inner class LocalBinder: Binder()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == "StopService") {
stopForeground(true)
stopSelf()
}
return START_STICKY
}
override fun onBind(intent: Intent): IBinder {
return binder
}
override fun onCreate() {
val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let {
notificationIntent -> PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// [...]
val notification: Notification = Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
// [...]
.build()
startForeground(1, notification)
}
}
}
Служба запускается и останавливается из приложения (не по каким-либо причинам):
Запуск:
serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder: MyService.LocalBinder = service as MyService.LocalBinder
}
override fun onServiceDisconnected(name: ComponentName?) {}
}
val startServiceIntent: Intent = Intent(this, MyService::class.java)
this.startForegroundService(startServiceIntent)
bindService(startServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
Останов:
unbindService(serviceConnection)
val stopIntent = Intent(this, MyService::class.java)
.setAction("StopService")
startService(stopIntent)
Это прекрасно работает дляодин циклНо когда я запускаю, останавливаю и затем перезапускаю службу, я получаю ANR, потому что объект Service не уничтожается и, следовательно, не создается снова, поэтому при втором запуске службы метод onCreate () не вызывается, а startForeground () не вызывается.Выполнено.
Как это должно быть реализовано?
- Нужно ли уничтожать служебный объект, чтобы убедиться, что создан новый?
- Должен ли янеобходимо создать уведомление и позвонить
startForeground
в onStartCommand
, а не onCreate
? - ...?
(Целью этой службы является сохранениеприложение живо, когда приложение закрыто)