Skip to content

Instantly share code, notes, and snippets.

@barbeau
Last active August 16, 2021 16:22
Show Gist options
  • Save barbeau/b2258df808d70a6bc2a9254d664e2727 to your computer and use it in GitHub Desktop.
Save barbeau/b2258df808d70a6bc2a9254d664e2727 to your computer and use it in GitHub Desktop.
Flow - lighweight architecture article - Service
@AndroidEntryPoint
class ForegroundOnlyLocationService : LifecycleService() {
...
// Data store (in this case, the SharedLocationManager) that the service will observe, injected via Hilt
@Inject
lateinit var repository: LocationRepository
// Get a reference to the Job from the Flow so we can stop it from UI events
private var locationFlow: Job? = null
...
fun subscribeToLocationUpdates() {
SharedPreferenceUtil.saveLocationTrackingPref(this, true)
// Binding to this service doesn't actually trigger onStartCommand(). That is needed to
// ensure this Service can be promoted to a foreground service, i.e., the service needs to
// be officially started (which we do here).
startService(Intent(applicationContext, ForegroundOnlyLocationService::class.java))
// Observe locations via Flow as they are generated by the repository
locationFlow = repository.getLocations()
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.onEach {
Log.d(TAG, "Service location: ${it.toText()}")
notificationManager.notify(
NOTIFICATION_ID,
generateNotification(currentLocation))
...
}
.launchIn(lifecycleScope)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val cancelLocationTrackingFromNotification =
intent?.getBooleanExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, false)
if (cancelLocationTrackingFromNotification == true) {
unsubscribeToLocationUpdates()
stopSelf()
}
// Tells the system not to recreate the service after it's been killed.
return super.onStartCommand(intent, flags, START_NOT_STICKY)
}
fun unsubscribeToLocationUpdates() {
locationFlow?.cancel()
SharedPreferenceUtil.saveLocationTrackingPref(this, false)
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment