My goal is to get a single pair of coordinates upon a received broadcast. What I've done so far is the following:
@Override
public void onReceive(Context context, Intent intent) {
// API 31 and above
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
locationManager.getCurrentLocation(LocationManager.FUSED_PROVIDER, null, context.getMainExecutor(), new Consumer<Location>() {
@Override
public void accept(Location location) {
if(location == null)
return;
MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
}
});
}
// Legacy (API < 31)
else{
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(locationCriteria, new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
}
@Override
public void onProviderEnabled(@NonNull String provider) {
Log.d("SmsHandler", "PROVIDER ENABLED");
}
@Override
public void onProviderDisabled(@NonNull String provider) {
Log.d("SmsHandler", "PROVIDER DISABLED");
}
}, null);
}
}
but it seems unstable. Should I use Services or something similar? Might I ask you why? I've read from the official documentation:
If this BroadcastReceiver was launched through a tag, then the object is no longer alive after returning from this function. This means you should not perform any operations that return a result to you asynchronously.
is that why? But to be honest I do not well understand what is being said very well (not so experienced with Android yet).
Furthermore, during some tests, if the user toggles the location just a second before the execution of the code above, neither getCurrentLocation()
nor onLocationChanged()
get fired, but, the next time the broadcast triggers onReceive()
, getCurrentLocation()
or onLocationChanged()
get executed twice (like it remembers it did not execute the last time).
Might you be so kind to help me? Thank you.