I'm writing an android app with android studio in java targetting API 29 devices. I've written a GPSReceiver (which extends BroadcastReceiver) and I need to know if GPS status has changed (ie add a location listener).
In earlier versions of Android, I know this could be accomplished with
ContentResolver contentResolver = context.getContentResolver();
int state = Settings.Secure.getInt(contentResolver, Settings.Secure.LOCATION_MODE);
Log.i(TAG, "GPS status changed, new state = " + state);
if (state == Settings.Secure.LOCATION_MODE_OFF)
do_smth;
else
do_smth_else;
And in Android 11 (API level 30) the next snippet seems to do it for me.
boolean state = intent.getIntExtra(LocationManager.EXTRA_LOCATION_ENABLED, -1);
if (state)
do_smth;
else
do_smth_else;
However, I don't know how get this exact behaviour in API 29.
You can try with this code, it works for me
public boolean isGPSOn() {
boolean check = false;
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
check = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
return check;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.