DougW DougW - 1 year ago 135
Android Question

Android get location or prompt to enable location service if disabled

I've found bits and pieces of this answer scattered through other posts, but I wanted to record it here for others.

How can I simply request the user's GPS and/or Network location and, if they haven't enabled the service, prompt them to do so?

Answer Source

If you want to capture the location on a button push, here's how you'd do it. If the user does not have a location service enabled, this will send them to the settings menu to enable it.

First, you must add the permission "android.permission.ACCESS_COARSE_LOCATION" to your manifest. If you need GPS (network location isn't sensitive enough), add the permission "android.permission.ACCESS_FINE_LOCATION" instead, and change the "Criteria.ACCURACY_COARSE" to "Criteria.ACCURACY_FINE"

Button gpsButton = (Button)this.findViewById(;
gpsButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // Start loction service
        LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE);

        Criteria locationCritera = new Criteria();

        String providerName = locationManager.getBestProvider(locationCritera, true);

        if (providerName != null && locationManager.isProviderEnabled(providerName)) {
            // Provider is enabled
            locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener);
        } else {
            // Provider not enabled, prompt user to enable it
            Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show();
            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

My outer class has this listener set up

private final LocationListener locationListener = new LocationListener() {

    public void onLocationChanged(Location location) {

    public void onProviderDisabled(String provider) {}

    public void onProviderEnabled(String provider) {}

    public void onStatusChanged(String provider, int status, Bundle extras) {}


Then, whenever you want to stop listening call this. You should at least make this call during your activity's onStop method.

LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download