Как правильно получать сообщения от сервера?
Разрабатываю мобильное приложение для Android, и есть поставленная задача - раз в 15 секунд, вне зависимости от того открыто ли приложение или нет, открывать TCP соединение, смотреть есть ли сообщения или нету. По Нетворкингу вопросов нету, но вот никак не могу добиться стабильной работы сервиса. Возможно я просто использую не тот сервис?
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
println("Service started: intent: $intent, flags: $flags, startId: $startId")
work()
if (!isWork) {
isWork = true
Thread(Runnable {
kotlin.run {
work()
}
}).start()
startForeground()
}
return START_REDELIVER_INTENT
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun stopService(name: Intent?): Boolean {
stopForeground(true)
stopSelf()
return super.stopService(name)
}
private fun startForeground() {
val name = "Channel name"
val descriptionText = "Service running in background!!!"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(channelID, name, importance)
mChannel.description = descriptionText
//register the channel with the system; you can`t change the importance
//or other notification behavior after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
startForeground(1, NotificationCompat.Builder(
this,
channelID
)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running background")
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setChannelId(channelID)
.build()
)
}
private fun work() {
while (isWork) {
println("${Calendar.getInstance().time} Service start working")
showNotify("${Calendar.getInstance().time}", "Service working", 30)
TimeUnit.SECONDS.sleep(3)
println("${Calendar.getInstance().time} Service done work, repeat after 2 sec")
TimeUnit.SECONDS.sleep(2)
}
}
Попробовал сделать сервис который стабильно работает - Xiaomi его убивает приблизительно в 23:30 Как добиться стабильной работы сервиса? Или всё же для стабильной работы нужно использовать Firebase ? Заранее спасибо!