Use below code to check. If it is disabled, dialog box will be generated

public void statusCheck() {
    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(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
Answer from Gautam on Stack Overflow
Top answer
1 of 8
131

Use below code to check. If it is disabled, dialog box will be generated

public void statusCheck() {
    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(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
2 of 8
19

Here is a simple way of programmatically enabling location like Maps app:

protected void enableLocationSettings() {
       LocationRequest locationRequest = LocationRequest.create()
             .setInterval(LOCATION_UPDATE_INTERVAL)
             .setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
             .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        LocationServices
                .getSettingsClient(this)
                .checkLocationSettings(builder.build())
                .addOnSuccessListener(this, (LocationSettingsResponse response) -> {
                    // startUpdatingLocation(...);
                })
                .addOnFailureListener(this, ex -> {
                    if (ex instanceof ResolvableApiException) {
                        // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().
                            ResolvableApiException resolvable = (ResolvableApiException) ex;
                            resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                        }
                    }
                });
 }

And onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (REQUEST_CODE_CHECK_SETTINGS == requestCode) {
        if(Activity.RESULT_OK == resultCode){
            //user clicked OK, you can startUpdatingLocation(...);

        }else{
            //user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
        }
    }
}

You can see the documentation here: https://developer.android.com/training/location/change-location-settings

🌐
Medium
droidbyme.medium.com › android-turn-on-gps-programmatically-d585cf29c1ef
Android Turn on GPS programmatically | by Droid By Me | Medium
January 2, 2019 - Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.
🌐
YouTube
youtube.com › watch
03 Enable Location Programmatically Android - YouTube
In this video we will learn how to enable location programmatically in a android device. How to enable "Location access" Programmatically in android.Turn on ...
Published   May 12, 2020
🌐
Jim Wilson
jwhh.com › 2013 › 03 › 20 › programmatically-enable-android-location-services
Programmatically Enable Android GPS and Location Services – Jim Wilson (a.k.a. hedgehogjim)
March 20, 2013 - The exact format of the screen the user sees will vary based on their Android version and device model, but the above code will always take them to the appropriate settings screen. On my Samsung device, the ACTION_LOCATION_SOURCE_SETTINGS screen looks like the following… · In general what I’ll do is use the LocationManager class to check for the availability of the required location services. If the services aren’t enabled, I’ll show an AlertDialog informing the user of what they need to do and then show the settings screen in the dialog’s click handler.
🌐
TutorialsPoint
tutorialspoint.com › how-to-enable-disable-the-gps-programmatically-in-android
How to enable/disable the GPS programmatically in Android?
August 2, 2019 - import android.content.Context; import android.content.Intent; import android.location.LocationManager; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button button; Context context; Intent intent1; TextView textview; LocationManager locationManager ; boolean GpsStatus ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a
🌐
Blogger
easy-ques.blogspot.com › 2016 › 08 › enable-location-service-gps-in-android.html
Android Easy: Enable Location Service (GPS) in android programmatically
August 2, 2016 - In Android it is possible to enable location services programmatically by using GoogleApiClient.
🌐
YouTube
youtube.com › technical coding
How to turn on loaction in android || Android studio tutorial - YouTube
In This Video I explain how to turn on device location programmatically in your android application.If you want to user to enable thier location what you do ...
Published   August 25, 2020
Views   10K
Top answer
1 of 13
154

This dialog is created by LocationSettingsRequest.Builder available in the Google Play Services.

You need to add a dependency to your app build.gradle:

compile 'com.google.android.gms:play-services-location:10.0.1'

Then you can use this minimal example:

private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i(TAG, "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i(TAG, "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

You can find the complete example here.

2 of 13
35

Follow the steps mentioned below

1) Create a LocationRequest as per your wish

LocationRequest mLocationRequest = LocationRequest.create()
           .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
           .setInterval(10 * 1000)
           .setFastestInterval(1 * 1000);

2) Create a LocationSettingsRequest.Builder

LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
               .addLocationRequest(mLocationRequest);
settingsBuilder.setAlwaysShow(true);

3) Get LocationSettingsResponse Task using following code

Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
              .checkLocationSettings(settingsBuilder.build());

Note: LocationServices.SettingsApi is deprecated so, use SettingsClient Instead.

4) Add a OnCompleteListener to get the result from the Task.When the Task completes, the client can check the location settings by looking at the status code from the LocationSettingsResponse object.

result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
    @Override
    public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
    try {
        LocationSettingsResponse response = 
                          task.getResult(ApiException.class);
        } catch (ApiException ex) {
            switch (ex.getStatusCode()) {
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    try {
                        ResolvableApiException resolvableApiException = 
                                 (ResolvableApiException) ex;
                            resolvableApiException
                                   .startResolutionForResult(MapsActivity.this, 
                                         LOCATION_SETTINGS_REQUEST);
                    } catch (IntentSender.SendIntentException e) {

                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                    break;
            }
        }
    }
});  

CASE 1: LocationSettingsStatusCodes.RESOLUTION_REQUIRED : Location is not enabled but, we can ask the user to enable the location by prompting him to turn on the location with the dialog (by calling startResolutionForResult).

CASE 2: LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE : Location settings are not satisfied. However, we have no way to fix the settings so we won't show the dialog.

5) OnActivityResult we can get the user action in the location settings dialog. RESULT_OK => User turned on the Location. RESULT_CANCELLED - User declined the location setting request.

Find elsewhere
🌐
Blogger
saravananandroid.blogspot.com › 2016 › 02 › enable-location-services-and-gps.html
Android Black Book: Enable Location Services and GPS programmatically (without navigating to the location settings)
February 5, 2016 - In this post, we have learn about enabling Location Services and GPS programmatically (without navigating to the location settings). First, 1) Add add google play services into android studio. 2) Create new project in android studio.
🌐
Medium
i-amvariable.medium.com › turning-on-gps-in-your-device-without-going-to-settings-12d1049225a3
Turning on GPS in your Device without going to Settings | by iamVariable | Medium
June 4, 2019 - We can turn on GPS programmatically in two ways. redirecting the user to location settings of a device (by code) another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.
🌐
Android Developers
developer.android.com › core areas › sensors and location › change location settings
Change location settings | Sensors and location | Android Developers
July 7, 2023 - In order to use the location services ... location provider, connect your app using the Settings Client, then check the current location settings and prompt the user to enable the required settings if needed....
🌐
Stack Overflow
stackoverflow.com › questions › 73402775 › how-to-enable-location-access-programmatically-in-android-app
java - How to enable Location access programmatically in Android app? - Stack Overflow
I am working on an application and on a specific button click I need to check whether location access is enabled or not in client-side development if location services are not enabled show the dialog prompt.
🌐
Instructables
instructables.com › circuits › mobile
Turn on GPS Programmatically in Android 4.4 or Higher : 12 Steps - Instructables
September 27, 2017 - PendingResult result = ...sultCallback(new ResultCallback() ... Now just connect phone to pc and turn on USB debugging mode in mobile and click on run in android studio....
🌐
Androidbugfix
androidbugfix.com › 2021 › 09 › how-to-enable-location-access.html
How to enable Location access programmatically in android? ~ AndroidBugFix
September 27, 2021 - I am working on map related android application and I need to check location access enable or not in client side development if location services is not enable show the dialog prompt. How to enable "Location access" Programmatically in android?
Top answer
1 of 3
1

This will help

public void locationChecker(GoogleApiClient mGoogleApiClient, final Activity activity) {
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
            builder.setAlwaysShow(true);
            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            // All location settings are satisfied. The client can initialize location
                            // requests here.
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the user
                            // a dialog.
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(
                                        activity, 1000);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.
                            break;
                    }
                }
            }

);
    }
2 of 3
0

Well found this in google play services 7.0...fusedapiprovider/settingsapi are api to be used.. http://android-developers.blogspot.in/2015/03/google-play-services-70-places-everyone.html?m=1 https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi

Happy coding..

Top answer
1 of 16
160

the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.

here's some example code i use

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.

private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}
2 of 16
77

All these answers are not allowed now. Here is the correct one:

For all those still looking for the Answer:

Here is how OLA Cabs and other such apps are doing it.

Add this in your onCreate

if (googleApiClient == null) {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(Login.this).build();
    googleApiClient.connect();
            LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    // **************************
    builder.setAlwaysShow(true); // this is the key ingredient
    // **************************

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                // All location settings are satisfied. The client can
                // initialize location
                // requests here.
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // Location settings are not satisfied. But could be
                // fixed by showing the user
                // a dialog.
                try {
                    // Show the dialog by calling
                    // startResolutionForResult(),
                    // and check the result in onActivityResult().
                    status.startResolutionForResult(Login.this, 1000);
                } catch (IntentSender.SendIntentException e) {
                    // Ignore the error.
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are not satisfied. However, we have
                // no way to fix the
                // settings so we won't show the dialog.
                break;
            }
        }
    });
}

These are the implmented methods:

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

Here is the Android Documentation for the same.

This is to help other guys if they are still struggling:

Edit: Adding Irfan Raza's comment for more help.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == 1000) {
         if(resultCode == Activity.RESULT_OK){
             String result=data.getStringExtra("result"); 
         } if (resultCode == Activity.RESULT_CANCELED) {
             //Write your code if there's no result 
         } 
    } 
} 
🌐
GitHub
github.com › sambhaji213 › Enable-GPS-Programmatically
GitHub - sambhaji213/Enable-GPS-Programmatically: As we know Turing on GPS in older Android was very easy but in 4.4 or in higher version we can't turn on GPS directly due to security reasons ,but we can turn on indirectly.
As we know Turing on GPS in older Android was very easy but in 4.4 or in higher version we can't turn on GPS directly due to security reasons ,but we can turn on indirectly. - sambhaji213/Enable-GPS-Programmatically
Author   sambhaji213
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-check-gps-is-on-or-off-in-android-programmatically
How to Check GPS is On or Off in Android Programmatically? | GeeksforGeeks
September 27, 2021 - { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring TextView and Button from the layout file val mTextView = findViewById<TextView>(R.id.text_view) val mButton = findViewById<Button>(R.id.button) // What happens when button is clicked mButton.setOnClickListener { // Calling Location Manager val mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager // Checking GPS is enabled val mGPS = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // Display the message into the string mTextView.text = mGPS.toString() } } }