0

I did a Foreground Service using Kotlin. It's works , but after seven hours running my service stop and my app returned to its first page (login page). But the only method to stop my service is executed when I click in a "stop service" button, so why my service is stopping after 7 hours if i didn't press any button? i'm using a moto g7, android 9.0

class RastreioService : Service() {

companion object {
    var serviceAtivado = false //service activated
}
override fun onBind(intent: Intent?): IBinder? {
    TODO("Not yet implemented")
}

override fun onCreate() {
    super.onCreate()
    serviceAtivado = true

    val notificationIntent = Intent(this, RastreioService::class.java)
    val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    val notification = Notification.Builder(this, "1")
        .setSmallIcon(R.drawable.ic_gps_ativo)
        .setContentTitle("Localização Sendo Acessada")
        .setContentText("A sua localização está sendo acessada")
        .setContentIntent(pendingIntent)
        .build()

    startForeground(1, notification)

    /*request location methods*/
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

    return START_NOT_STICKY
}

override fun onDestroy() {
    serviceAtivado = false
    super.onDestroy()
    this.gerenciadorDeLocalizacao.DesativarBuscaPorLocalizaca()
}

}
Rodrigo R
  • 311
  • 3
  • 11
  • Which device you are using? this device is having stock or custom ROM. look out this answers, https://stackoverflow.com/questions/52425222/foreground-service-getting-killed-from-oreo – mdroid Jul 02 '20 at 13:38
  • i'm using a moto g7, android 9.0 – Rodrigo R Jul 02 '20 at 13:47
  • Is there any option in device setting like an Auto startup or battery optimization? If it has, checks your app enables the permission or not. – mdroid Jul 02 '20 at 13:49

2 Answers2

0

A foreground service can still be killed by the OS, you have no guarantees that the service will last forever. A foreground service just makes it less likely to be killed

tyczj
  • 71,600
  • 54
  • 194
  • 296
0

OS still can shut down services if it feels like it needs to, but it can be resumed afterward. on onStartCommand you are returning START_NOT_STICKY you can use which does not re start the service. You can use START_REDELIVER_INTENT to save progress of your service and re start it from where it left of. Link to the docs