208

On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?

naXa
  • 26,677
  • 15
  • 154
  • 213
Marcus
  • 8,321
  • 4
  • 19
  • 23

11 Answers11

462

Best way seems to be the following:

 final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}
Chris Rae
  • 5,457
  • 2
  • 31
  • 48
Marcus
  • 8,321
  • 4
  • 19
  • 23
  • 1
    Mainly it is about firing up an intend to see the GPS config, see http://github.com/marcust/HHPT/blob/master/src/org/thiesen/hhpt/ui/activity/main/MainActivity.java for details. – Marcus Nov 29 '09 at 22:14
  • 3
    Nice snippet of code. I removed the @SuppressWarnings and am not receiving any warnings... perhaps they are unnecessary? – span Aug 16 '12 at 11:32
  • 30
    I would advise declaring `alert` for the whole activity so you can dismiss it in onDestroy to avoid a memory leak (`if(alert != null) { alert.dismiss(); }`) – Cameron Jan 24 '13 at 15:51
  • So what if I am on Battery Saving, will this still work? – Prakhar Mohan Srivastava May 26 '15 at 08:49
  • 3
    @PrakharMohanSrivastava if your location settings are on Power-Saving, this will return false, however `LocationManager.NETWORK_PROVIDER` will return true – Tim Feb 18 '16 at 14:06
  • It works fine, but you should also add `dialog.cancel` when clicking the positive button, otherwise the dialog stays even if we enable the GPS. – TDG Jun 24 '16 at 16:53
  • is there any way to listen if the GPS is turned off, not just check once-off? – The Clueless Programmer Aug 11 '16 at 14:55
  • @TheCluelessProgrammer you were probably looking for [How to detect when user turn on/off gps state?](https://stackoverflow.com/questions/15778807/how-to-detect-when-user-turn-on-off-gps-state). – Sufian Oct 30 '18 at 19:05
130

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

Here is a simple program to Check.

GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Your java class file should be

public class ExampleApp extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    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();
    }
}

The output will looks like

enter image description here

enter image description here

beryllium
  • 29,214
  • 15
  • 99
  • 123
  • 1
    Nothing happens when I try your function. I got no errors when I test it though. – Airikr Apr 02 '12 at 00:41
  • I got it working! :) Many thanks but I can't vote up until you have edited your answer :/ – Airikr Apr 02 '12 at 07:41
  • 3
    no problem @Erik Edgren you get solution so i m happy ENjoy...!! –  Apr 02 '12 at 08:28
  • @user647826: Excellent! Works nicely. You saved my night – Addi May 23 '12 at 21:57
  • 1
    A piece of advice: declare `alert` for the whole activity so you can dismiss it in `onDestroy()` to avoid a memory leak (`if(alert != null) { alert.dismiss(); }`) – naXa Jul 10 '16 at 20:45
38

yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.

Check if location providers are available

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider != null){
        Log.v(TAG, " Location providers: "+provider);
        //Start searching for location and update the location text when update available
        startFetchingLocation();
    }else{
        // Notify users and show settings if they want to enable GPS
    }

If the user want to enable GPS you may show the settings screen in this way.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

And in your onActivityResult you can see if the user has enabled it or not

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE && resultCode == 0){
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if(provider != null){
                Log.v(TAG, " Location providers: "+provider);
                //Start searching for location and update the location text when update available. 
// Do whatever you want
                startFetchingLocation();
            }else{
                //Users did not switch on the GPS
            }
        }
    }

Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.

Guido
  • 42,125
  • 24
  • 113
  • 167
achie
  • 4,565
  • 7
  • 41
  • 58
  • 2
    hi, i have a similar problem...can you briefly explain, what the "REQUEST_CODE" is and what it's for? – poeschlorn May 06 '10 at 08:29
  • 2
    @poeschlorn Anna posted the link to detailed below. In simple terms, the RequestCode allows you to use `startActivityForResult` with multiple intents. When the intents return to your activity, you check the RequestCode to see which intent is returning and respond accordingly. – Farray Feb 17 '11 at 18:10
  • 2
    The `provider` can be an empty string. I had to change the check to `(provider != null && !provider.isEmpty())` – Pawan Apr 25 '14 at 09:49
  • As provider can be " ",consider using int mode = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE); If mode=0 GPS is off – Levon Petrosyan Dec 06 '17 at 13:55
31

Here are the steps:

Step 1: Create services running in background.

Step 2: You require following permission in Manifest file too:

android.permission.ACCESS_FINE_LOCATION

Step 3: Write code:

 final LocationManager manager = (LocationManager)context.getSystemService    (Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
  Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show(); 
else
  Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();

Step 4: Or simply you can check using:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

Step 5: Run your services continuously to monitor connection.

wojciii
  • 4,095
  • 1
  • 27
  • 37
Rakesh
  • 2,364
  • 25
  • 27
18

Yes you can check below is the code:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
Thomas Vos
  • 11,085
  • 4
  • 24
  • 63
Arun kumar
  • 1,794
  • 3
  • 20
  • 27
10

This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};
Code Spy
  • 7,520
  • 3
  • 57
  • 39
8

Here is the snippet worked in my case

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`

Kashif Ahmad
  • 149
  • 1
  • 10
8

In Kotlin: How to check GPS is enable or not

 val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            checkGPSEnable()
        } 

 private fun checkGPSEnable() {
        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
                    ->
                    startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                })
                .setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })
        val alert = dialogBuilder.create()
        alert.show()
    }
Haider Saleem
  • 609
  • 1
  • 7
  • 12
safal bhatia
  • 139
  • 1
  • 4
6

GPS will be used if the user has allowed it to be used in its settings.

You can't explicitly switch this on anymore, but you don't have to - it's a privacy setting really, so you don't want to tweak it. If the user is OK with apps getting precise co-ordinates it'll be on. Then the location manager API will use GPS if it can.

If your app really isn't useful without GPS, and it's off, you can open the settings app at the right screen using an intent so the user can enable it.

3

In your LocationListener, implement onProviderEnabled and onProviderDisabled event handlers. When you call requestLocationUpdates(...), if GPS is disabled on the phone, onProviderDisabled will be called; if user enables GPS, onProviderEnabled will be called.

kittykittybangbang
  • 2,296
  • 4
  • 14
  • 26
1

Kotlin Solution :

private fun locationEnabled() : Boolean {
    val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
Udit Pandya
  • 41
  • 1
  • 6