【问题标题】:Foreground Service Stopself after hours working下班后前台服务停止
【发布时间】:2020-07-02 13:31:15
【问题描述】:

我使用 Kotlin 做了一个前台服务。它可以工作,但是在运行我的服务停止七个小时后,我的应用程序返回到它的第一页(登录页面)。但是,当我单击“停止服务”按钮时,停止服务的唯一方法是执行,那么如果我没有按任何按钮,为什么我的服务会在 7 小时后停止?我正在使用 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()
}

}

【问题讨论】:

  • 您使用的是哪种设备?此设备有库存或自定义 ROM。看看这个答案,stackoverflow.com/questions/52425222/…
  • 我使用的是 moto g7,android 9.0
  • 设备设置中是否有任何选项,例如自动启动或电池优化?如果有,请检查您的应用是否启用了权限。

标签: android kotlin mobile service


【解决方案1】:

如果感觉需要,操作系统仍然可以关闭服务,但之后可以恢复。 在onStartCommand 你正在返回START_NOT_STICKY 你可以使用 which 不重新启动服务。 您可以使用 START_REDELIVER_INTENT 来保存您的服务进度并从它离开的地方重新启动它。 Link 给文档

【讨论】:

    【解决方案2】:

    前台服务仍然可以被操作系统杀死,您无法保证该服务将永远持续下去。前台服务只会降低它被杀死的可能性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2017-01-25
      • 2023-04-03
      • 2015-12-17
      相关资源
      最近更新 更多