I was working on a project, where I need to detect location of the device. User needs to tap a button in configuration page and location should be detected.
Detection only by GPS didn’t work on some Samsung devices. Pretty annoying problem, I should say.
So, I added some other methods to get coarse location in case GPS is not accessible for some reason:
private class RetrieveLocation extends AsyncTask
{
private ProgressDialog progress = null;
private double lat ;
private double lng ;
private LocationManager lm;
private LocationListener locationListener;
@Override
protected Void doInBackground(Void... params) {
Looper.myLooper().prepare(); //This string makes magic. Without this string, there was an exception "Cant Create Handler Inside Thread That Has Not Called Looper Prepare in Android"
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
// Here starts fine location detection
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
30000,
30,
locationListener);
Location locationM = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationM != null) {
lat = Double.parseDouble(numberFormat.format(locationM.getLatitude()));
lng = Double.parseDouble(numberFormat.format(locationM.getLongitude()));
}else{
// If fine location is not detected, we are trying to get network location
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
progress.setMessage("Mobile network location");
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
30000,
30,
locationListener);
locationM = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (locationM != null) {
lat = Double.parseDouble(numberFormat.format(locationM.getLatitude()));
lng = Double.parseDouble(numberFormat.format(locationM.getLongitude()));
}
}else{
// if we failed again, we try we get coarse location from passive providers
progress.setMessage("Coarse location");
lm.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
30000,
30,
locationListener);
locationM = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (locationM != null) {
lat = Double.parseDouble(numberFormat.format(locationM.getLatitude()));
lng = Double.parseDouble(numberFormat.format(locationM.getLongitude())); }
}
}
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(
SettingsPage.this, null, "Detecting location...");
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
// After the search is finished, we can do something with the results lat and lng.
progress.dismiss();
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Don’t forget to add to Manifest.xml