我有一个前台服务,使用LocationManager和Geofences跟踪某些设备。 我注意到,当我在Moto g7中运行服务时,在3或4个小时后,我的服务停止了,这种情况发生时,如果我按下设备的电源按钮,我的设备就会“唤醒”,这会使我的服务恢复运行! 我想要一个无限的前台服务,并且我的服务具有唤醒锁,这不应该使我的服务在手机休眠时不会停止吗?
class myService : Service() {
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myService::lock").apply {
acquire()
}
}
startForegroundService()
/*business rules*/
return START_STICKY
}
override fun onDestroy() {
super.onDestroy()
wakeLock?.let {
if (it.isHeld) {
it.release()
}
}
}
private fun startForegroundService(){
var notification = createNotification()
val idService = 1
startForeground(idService, notification)
}
private fun createNotification(): Notification {
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()
return notification
}
}