В приложении создаю сервис, который в фоне обновляет местоположение. При полном закрытии и открытии приложения не могу разбиндить уведомление и его удалить. Для удобства написал мененджер сервиса.
var locationUpdateService: LocationUpdateService? = null
var isBound = false
val serviceClass = LocationUpdateService::class.java
val serviceIntent = Intent(appContext, serviceClass)
private val myConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
val binder = iBinder as LocationUpdateService.LocationUpdateServiceBinder
locationUpdateService = binder.getService()
isBound = true
}
override fun onServiceDisconnected(componentName: ComponentName) {
isBound = false
}
}
fun startLocationUpdateForeground() {
if (!isServiceRunning(serviceClass.javaClass)) {
appContext.startService(serviceIntent)
appContext.bindService(serviceIntent, myConnection, AppCompatActivity.BIND_AUTO_CREATE)
} else {
Logger.logE("Service already running.")
MakeToast.makeInfo("Service already running.")
appContext.bindService(serviceIntent, myConnection, AppCompatActivity.BIND_AUTO_CREATE)
}
}
fun stopLocationUpdateForeground() {
try {
appContext.unbindService(myConnection)
} catch (e: IllegalArgumentException) {
Logger.logE("Error Unbinding Service.")
}
if (isServiceRunning(serviceClass)) {
appContext.stopService(serviceIntent)
} else {
Logger.logE("Service not running.")
MakeToast.makeInfo("Service not running.")
}
}
private fun isServiceRunning(serviceClass: Class<*>): Boolean {
val activityManager =
appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// Loop through the running services
for (service in activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
Сам сервис:
class LocationUpdateService : Service() {
companion object {
const val CHANNEL_ID = "CHANNEL_ID "
const val CHANNEL_NAME = "CHANNEL_NAME "
}
private val myBinder = LocationUpdateServiceBinder()
private lateinit var mNotification: Notification
private val mNotificationId: Int = 999
private val fusedLocationProviderClient: FusedLocationProviderClient? =
LocationServices.getFusedLocationProviderClient(appContext)
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
for (location in locationResult.locations) {
val loc = Location(
location.latitude,
location.longitude
)
MakeToast.makeError(loc.toString())
updateMyLocation(loc)
}
}
}
private fun settingsLocationRequests(): LocationRequest? {
val locationRequest = LocationRequest.create()
locationRequest.interval = 120000
locationRequest.smallestDisplacement = 10F;
locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
return locationRequest
}
override fun onBind(intent: Intent): IBinder {
return myBinder
}
inner class LocationUpdateServiceBinder : Binder() {
fun getService(): LocationUpdateService {
return this@LocationUpdateService
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Logger.logI("Service started.")
getNotification(applicationContext)
startLocationUpdates(locationCallback)
return Service.START_STICKY
}
override fun onDestroy() {
super.onDestroy()
Logger.logI("Service destroyed.")
stopLocationUpdates(locationCallback)
stopForeground(true)
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
stopSelf()
}
fun startLocationUpdates(locationCallback: LocationCallback?) {
if (!checkSelfPermission()) {
return
}
settingsLocationRequests()?.let {
fusedLocationProviderClient!!.requestLocationUpdates(
it,
locationCallback,
Looper.getMainLooper()
)
}
}
fun stopLocationUpdates(locationCallback: LocationCallback?) {
fusedLocationProviderClient!!.removeLocationUpdates(locationCallback)
}
private fun updateMyLocation(location: Location) {
...
}
...