Reputation: 147
I have a problem which happens only on real devices, whereas on Android emulators it works fine.
I need to work on current coordinates when a Broadcast is received. This is the code:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isLocationEnabled()){
enableLocation(context);
}
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(locationCriteria, new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
Log.d("SmsHandler", "Going to send coordinates: " + location.getLatitude() + " " + location.getLongitude());
doThings();
}
@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);
}
Which works fine if location is enabled (doThings()
gets correctly called).
If the location is not enabled, enableLocation()
is called. This method is able (successfully) to enable the "Location" toggle on the smartphone (through the WRITE_SECURE_SETTING permission).
This is its code to give more clarity, but it should work just fine. You can think of it as the user turns on Location on by themselves
public static boolean enableLocation(Context context){
if (Build.VERSION.SDK_INT < 19) {
return false;
}
if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED){
return false;
}
return android.provider.Settings.Secure.putInt(context.getContentResolver(),
android.provider.Settings.Secure.LOCATION_MODE,
android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
}
Now:
2022-11-08 22:08:12.048 : PROVIDER DISABLED
2022-11-08 22:08:12.120 : PROVIDER ENABLED
and does not prompt Going to send coordinates:
Why? I know it's an edge case but I'd like to fix this. Thank you.
Update Adding Thread.sleep(1000L)
before location is requested solves the issue, but I don't like it. Then why does it work when the app is in foreground? And is there a better approach to this?
Upvotes: 0
Views: 61