Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Monitoring GPS and Permission checks using Live...

Monitoring GPS and Permission checks using LiveData

In our last project, we had to implement checks to ensure GPS is enabled on the device and Location Permission is granted by the user. It is important to highlight that both are critically needed to ensure the app can perform Location Tracking in background.

Our best bet was to inform visually when the app is in the foreground or background in order to encourage the user to fulfill one or both of these requirements. This was only possible when UI (Activity/Fragment) and Service can listen to changes in GPS and Runtime Permission and react accordingly.

I faced several challenges while doing that and decided to share my learnings and solution.

Wahib Ul Haq

August 08, 2018
Tweet

More Decks by Wahib Ul Haq

Other Decks in Technology

Transcript

  1. LiveData is an observable data holder and lifecycle-aware. It lets

    the components in your app, usually the UI, observe LiveData objects for changes.
  2. sealed class GpsStatus { data class GpsIsDisabled(val message: Int) :

    GpsStatus() data class GpsIsEnabled(val message: Int) : GpsStatus() }
  3. private val gpsSwitchStateReceiver = object : BroadcastReceiver() { override fun

    onReceive(context: Context, intent: Intent) = checkGpsAndReact() }
  4. private val gpsObserver = Observer<GpsStatus> { status -> status?.let {

    when (status) { is GpsStatus.GpsIsEnabled -> { //update UI } is GpsStatus.GpsIsDisabled -> { //update UI } } } }
  5. sealed class PermissionStatus { data class Granted(val message: Int) :

    PermissionStatus() data class Denied(val message: Int) : PermissionStatus() }
  6. override fun onActive() = handlePermissionCheck() private fun handlePermissionCheck() { val

    isPermissionGranted = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED }
  7. private fun handlePermissionCheck() { val isPermissionGranted = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==

    PackageManager.PERMISSION_GRANTED if (isPermissionGranted) postValue(PermissionStatus.Granted(R.string.permission_status_granted)) else postValue(PermissionStatus.Denied(R.string.permission_status_denied_show_notif)) }
  8. private val gpsObserver = Observer<GpsStatus> { status -> status?.let {

    handleGpsStatus(status) } } private val permissionObserver = Observer<PermissionStatus> { status -> status?.let { handlePermissionStatus(status) } }
  9. private val pairObserver = Observer<Pair<PermissionStatus, GpsStatus>> { pair -> pair?.let

    { handlePermissionStatus(pair.first) handleGpsStatus(pair.second) } }
  10. More Stuff SingeLiveEvent A lifecycle-aware observable that sends only new

    updates after subscription, used for events like navigation and Snackbar messages.