Как исправить Location Background Service в Android?
Сервис вызывается в MainActivity. При сворачивании приложения координаты определяются 1 раз и всё. Потом через некоторое время сервис убивается.
class MyServiceNew : Service() {
val TAG = "APK: CONSOLE - SERVICE"
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d(TAG, "My Service")
return START_STICKY
}
override fun onCreate() {
Log.e(TAG, "onCreate")
super.onCreate()
fusedLocationClient = FusedLocationProviderClient(this)
updateLocationTracking()
}
private fun updateLocationTracking() {
val request = LocationRequest().apply {
interval = 3000
fastestInterval = 1000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
fusedLocationClient.requestLocationUpdates(
request,
locationCallback,
Looper.getMainLooper()
)
}
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
super.onLocationResult(result)
result.lastLocation
onLocationChanged(result.lastLocation)
}
}
override fun onDestroy() {
Log.e(TAG, "onDestroy")
//stopLocationUpdates()
}
private fun onLocationChanged(location: Location) {
Log.d(TAG, "onLocationChanged $location")
}
}
Решение. Действительно. Как подсказал в комментариях @Wlad , нужно было перевести сервис с Background в Foreground. Для этого нужно было создать канал уведомлений и запустить процесс startForeground в методе onStartCommand
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d(TAG, "My Service")
createNotificationChannel()
val myIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, myIntent, PendingIntent.FLAG_MUTABLE)
val notification = NotificationCompat.Builder(this, "channel1")
.setContentTitle("My app")
.setContentText("Our app runnig")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
updateLocationTracking()
return START_STICKY
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel("channel1", "Foreg Notif", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}