Reputation: 1821
In my app I will check the GPS is enabled or not. If not enabled i will redirect the page to GPS settings.
After enable the GPS i will get the location from LocationManager. But I can not get the location.
Here I attached my code.
if (isGPSEnabled())
{
getLocation();
}
private boolean isGPSEnabled() {
boolean gpsEnabled = false;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
gpsEnabled = true;
return gpsEnabled;
} else {
showGPSDisabledAlertToUser();
}
return gpsEnabled;
}
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder
.setMessage(
"GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
}
}
public void onLocationChanged(Location location) {
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
}
Please tell me what mistake i did?
Thanks in advance..
Upvotes: 1
Views: 3926
Reputation: 307
I think the problem is that you never ask for a new location from LocationManager.
private void getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
locationManager.requestSingleUpdate(provider, myLocationListener, null);
}
}
Upvotes: 2