Merge pull request #179 from TouchInstinct/ubrir_mastur/huawei_location_live_data

Add HuaweiLocationLiveData
This commit is contained in:
Kirill Nayduik 2020-10-27 11:27:58 +03:00 committed by GitHub
commit 79c9336c33
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 63 additions and 0 deletions

View File

@ -16,4 +16,6 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "com.google.android.gms:play-services-location:$versions.location"
implementation "com.huawei.hms:location:$versions.hmsLocation"
}

View File

@ -0,0 +1,61 @@
package ru.touchin.livedata.location
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.Context
import android.location.Location
import androidx.annotation.RequiresPermission
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.huawei.hms.location.FusedLocationProviderClient
import com.huawei.hms.location.LocationAvailability
import com.huawei.hms.location.LocationCallback
import com.huawei.hms.location.LocationRequest
import com.huawei.hms.location.LocationResult
import com.huawei.hms.location.LocationServices
class HuaweiLocationLiveData(
context: Context,
private val request: LocationRequest
) : LiveData<Location>() {
private val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
postValue(result.lastLocation)
}
override fun onLocationAvailability(availability: LocationAvailability) {
if (!availability.isLocationAvailable) postValue(null)
}
}
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
override fun observe(owner: LifecycleOwner, observer: Observer<in Location>) {
super.observe(owner, observer)
}
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
override fun onActive() {
startListening()
}
override fun onInactive() {
stopListening()
}
private fun stopListening() {
fusedLocationClient.removeLocationUpdates(locationCallback)
}
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
private fun startListening() {
fusedLocationClient.requestLocationUpdates(
request,
locationCallback,
null
)
}
}