Hello StackOverflow 🙂
I have created some code inside my onStart(); method to ensure that the user has GPS enabled so i can figure out in which country is he right now. If GPS is disabled, it should show an alert dialog prompting the user to enable GPS before using the app.
For some reason, it seems like that whole chunk of code isn’t working. I have disabled GPS and nothing is happening, no dialog and nothing like that. Why is this happening?
Here is my code:
@Override
protected void onStart() {
super.onStart();
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder code = new Geocoder(TipCalculatorActivity.this);
try {
Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
CountryName = adr.getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!gpsEnabled) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS connectivity to determine your current country, and deliver you accurate tip ratings. Do you wish to turn GPS on?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
TipCalculatorActivity.this.enableLocationSettings();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
TipCalculatorActivity.this.finish();
System.exit(1);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
Thanks a lot for any help 🙂
Is may be returning null in your case since your mobile has no cached locations.
So change your code to
If you need to query current Location.Then you need to have active Data connection or GPS turned on.
Following Snippet will help you
Finally make sure you have added following permissions.