Displaying a dialog in android to prompt user to enable GPS

The following code snippet can be used to prompt a user to enable GPS in android:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;

class Utils {
    public static void displayPromptForEnablingGPS(
        final Activity activity)
    {
        final AlertDialog.Builder builder =
            new AlertDialog.Builder(activity);
        final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
        final String message = "Enable either GPS or any other location"
            + " service to find current location.  Click OK to go to"
            + " location services settings to let you do so.";

        builder.setMessage(message)
            .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int id) {
                        activity.startActivity(new Intent(action));
                        d.dismiss();
                    }
            })
            .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int id) {
                        d.cancel();
                    }
            });
        builder.create().show();
    }
}

As you can see, the action Settings.ACTION_LOCATION_SOURCE_SETTINGS is used to start the activity to change the GPS/Location source settings.

A related example use case can be found at: https://github.com/kbsbng/Sunrise-Sunset-Calculator/blob/master/src/com/kbsbng/androidapps/sunrise_sunset_calculator/GpsOrNetworkPrompt.java.

Comments

Unknown said…
Not Working Dude...