Created
June 29, 2018 03:06
-
-
Save niusounds/8a3c8a1ffe581220aaeae7c315498e1a to your computer and use it in GitHub Desktop.
Location wrapper for LiveData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.Manifest | |
import android.annotation.SuppressLint | |
import android.app.Activity | |
import android.arch.lifecycle.LiveData | |
import android.content.Context | |
import android.content.pm.PackageManager | |
import android.location.Location | |
import android.os.Looper | |
import android.support.v4.app.ActivityCompat | |
import android.support.v4.content.ContextCompat | |
import com.google.android.gms.location.LocationCallback | |
import com.google.android.gms.location.LocationRequest | |
import com.google.android.gms.location.LocationResult | |
import com.google.android.gms.location.LocationServices | |
class LocationLiveData(private val context: Context, | |
private val locationRequest: LocationRequest = LocationRequest()) : LiveData<Location>() { | |
private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) | |
private val callback = object : LocationCallback() { | |
override fun onLocationResult(locationResult: LocationResult) { | |
super.onLocationResult(locationResult) | |
value = locationResult.lastLocation | |
} | |
} | |
@SuppressLint("MissingPermission") | |
override fun onActive() { | |
super.onActive() | |
if (hasPermission(context)) { | |
fusedLocationClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper()) | |
} | |
} | |
override fun onInactive() { | |
super.onInactive() | |
fusedLocationClient.removeLocationUpdates(callback) | |
} | |
companion object { | |
fun hasPermission(context: Context): Boolean { | |
return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED | |
} | |
fun requestPermission(activity: Activity, requestCode: Int) { | |
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), requestCode) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment