Since this the new Android 8 update came out there are many limitations imposed on how background services work.
So my app needs to fetch in background the user's location regularly and for that, I considered using FusedLocationProviderClient suggested by Android Website. After the location has been fetched I just need to some simple work with the info.
Right now I developed this sample of code:
private fun updateLocation(){
//Location Request
val mLocationRequest = LocationRequest();
mLocationRequest.smallestDisplacement = 1000f;
mLocationRequest.interval = 5*60*1000;
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
//Location Provider
val mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
//Check Location Permission
if(PermissionChecker.checkSelfPermission(this,ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED)
//Request Location
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,locationCallback,null);
}
private val locationCallback = object:LocationCallback(){
override fun onLocationResult(locationResult: LocationResult?) {
doSomeWork()
}
}
So I have a question:
If I want my app to get updates even if the activity has been closed, it sounds like a Service's job right? But with this new updates, my service doesn't run forever so it will be killed sooner or later.
Using a regularly scheduled job, the service will be launched when the conditions are met but it seems kinda weird to schedule regular jobs to update the location instead of using a unique service that makes use of the Interval and SmallestDisplacement for new updates.
The requestLocationUpdates() invoke his callback every time the LocationRequest's conditions are met (interval and/or smallestDisplacement in this sample). That's what I'm trying to accomplish, I want a job that requests for location updates, not multiple jobs rescheduled as I need the updates that request for the location.
Is there any other better way to accomplish what I'm trying to say or I need this new approach of scheduled jobs?
Anyways, sorry for this messy post, it's my first question on Stack Overflow Thanks :)
The FusedLocationProviderClient provides several methods to retrieve device location information. Choose from one of the following, depending on your app's use case: getLastLocation() gets a location estimate more quickly and minimizes battery usage that can be attributed to your app.
The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.
Use the Geofencing API for that. That gives you an intent that you can handle in an IntentService. No notification required.
All you need to do is to setup a new geofence with 1000m radius at the current position and wait for the user to leave.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With