You can use the below code to check whether gps provider and network providers are enabled or not.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
    new AlertDialog.Builder(context)
        .setMessage(R.string.gps_network_not_enabled)
        .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        })
        .setNegativeButton(R.string.Cancel,null)
        .show();    
}

And in the manifest file, you will need to add the following permissions

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Answer from Shankar Agarwal on Stack Overflow
Top answer
1 of 16
418

You can use the below code to check whether gps provider and network providers are enabled or not.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
    new AlertDialog.Builder(context)
        .setMessage(R.string.gps_network_not_enabled)
        .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        })
        .setNegativeButton(R.string.Cancel,null)
        .show();    
}

And in the manifest file, you will need to add the following permissions

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
2 of 16
231

I use this code for checking:

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    }else{
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }


} 
Top answer
1 of 4
8

The following code check if location is enabled or not. If not enabled it shows alert dialog.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }catch (Exception ex){}
    try{
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }catch (Exception ex){}
    if(!gps_enabled && !network_enabled){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
        dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {                 
                Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                Startup.this.startActivity(myIntent);                    
            }
        });
        dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
        dialog.show();
    }
2 of 4
0

Is your code working ? But you are asking about when do you need to check GPS ?? It depends on your goal, what your app is responsible for, if it is GPS tracker, you can check it when first activity starts, or if is not major function in your app, you can just notify but continue working.

I have dealt with the same problem of checking GPS, there are two types of GPS providers available in Android Framework now :

  1. Using Google Play Services (it is recommended to use)
  2. Using old Location Manager

So I have implemented two strategies for the case when device doesn't have google play services installed.

Base Strategy interface.

public interface BaseLocationStrategy {
    void startListeningForLocationChanges(LocationChangesListener locationListener);

    void stopListeningForLocationChanges();

    void setPeriodicalUpdateEnabled(boolean enable);

    void setPeriodicalUpdateTime(long time);

    Location getLastLocation();

    void initLocationClient();

}

Location change listener interface

public interface LocationChangesListener {
    void onLocationChanged(Location location);
    void onConnected();
    void onConnectionStatusChanged();
    void onFailure(String failureMessage);

}

And concrete implementation

public class GooglePlayServiceLocationStrategy implements
        BaseLocationStrategy,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    private Context mAppContext;
    private Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private LocationChangesListener mLocationListener;
    private boolean mUpdatePeriodically = false;
    private LocationRequest mLocationRequest;
    private static GooglePlayServiceLocationStrategy INSTANCE;
    // Location updates intervals in sec
    private static long UPDATE_INTERVAL = 10000; // 10 sec
    private static long FASTEST_INTERVAL = 5000; // 5 sec
    private static long DISPLACEMENT = 10; // 10 meters

    private GooglePlayServiceLocationStrategy(Context context) {
        this.mAppContext = context;
    }

    @Override
    public void startListeningForLocationChanges(LocationChangesListener locationListener) {
        this.mLocationListener = locationListener;
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void stopListeningForLocationChanges() {
        mLocationListener = null;
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
            mGoogleApiClient.disconnect();
        }
    }

    public static BaseLocationStrategy getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new GooglePlayServiceLocationStrategy(context);
            INSTANCE.initLocationClient();
        }
        return INSTANCE;
    }

    @Override
    public void setPeriodicalUpdateEnabled(boolean enable) {
        this.mUpdatePeriodically = enable;
    }

    @Override
    public void setPeriodicalUpdateTime(long time) {
        UPDATE_INTERVAL = time < FASTEST_INTERVAL ? FASTEST_INTERVAL : time;
    }

    @Override
    public Location getLastLocation() {
        return this.mLastLocation;
    }

    @Override
    public void initLocationClient() {
        mGoogleApiClient = buildGoogleApiClient();
        mLocationRequest = createLocationRequest();
    }

    protected synchronized GoogleApiClient buildGoogleApiClient() {
        return new GoogleApiClient.Builder(mAppContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationListener.onConnected();
        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);
        if (mUpdatePeriodically) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        mLocationListener.onConnectionStatusChanged();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        mLocationListener.onFailure(connectionResult.getErrorMessage());
    }

    /**
     * Starting the location updates
     */
    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    /**
     * Creating location request object
     */
    protected LocationRequest createLocationRequest() {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(UPDATE_INTERVAL);
        locationRequest.setFastestInterval(FASTEST_INTERVAL);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
        return locationRequest;
    }

    /**
     * Stopping location updates
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        mLocationListener.onLocationChanged(location);
    }


}

And finally for old way

public class LocationManagerStrategy implements BaseLocationStrategy, LocationListener {
    private Context mAppContext;
    private LocationManager mLocationManager;
    private Location mLastLocation;
    private LocationChangesListener mLocationListener;
    private boolean mUpdatePeriodically = false;
    private static LocationManagerStrategy INSTANCE;
    // Location updates intervals in sec
    private static long UPDATE_INTERVAL = 10000; // 10 sec
    private static long FASTEST_INTERVAL = 5000; // 5 sec
    private static long DISPLACEMENT = 10; // 10 meters

    private LocationManagerStrategy(Context context) {
        this.mAppContext = context;
    }

    public static LocationManagerStrategy getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LocationManagerStrategy(context);
            INSTANCE.initLocationClient();
        }
        return INSTANCE;
    }

    @Override
    public void startListeningForLocationChanges(LocationChangesListener locationListener) {
        mLocationListener = locationListener;
        try {

            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    UPDATE_INTERVAL,
                    DISPLACEMENT, this);
        } catch (SecurityException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void stopListeningForLocationChanges() {
        try {
            mLocationManager.removeUpdates(this);
        } catch (SecurityException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void setPeriodicalUpdateEnabled(boolean enable) {
        mUpdatePeriodically = enable;
    }

    @Override
    public void setPeriodicalUpdateTime(long time) {
        UPDATE_INTERVAL = time;
    }

    @Override
    public Location getLastLocation() {
        if (mLastLocation == null) {
            try {
                mLastLocation = mLocationManager.getLastKnownLocation(getBestProvider());
            } catch (SecurityException securityException) {
                return null;
            }
        }
        return mLastLocation;
    }

    private String getBestProvider() {
        Criteria criteria = new Criteria();
        return mLocationManager.getBestProvider(criteria, false);
    }

    @Override
    public void initLocationClient() {
        mLocationManager = (LocationManager) mAppContext.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        mLocationListener.onLocationChanged(location);
        if (!mUpdatePeriodically) {
            this.stopListeningForLocationChanges();
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        mLocationListener.onConnectionStatusChanged();
    }

    @Override
    public void onProviderEnabled(String provider) {
        mLocationListener.onConnected();
    }

    @Override
    public void onProviderDisabled(String provider) {
        mLocationListener.onFailure(provider);
    }
}
Discussions

check location service is enable or not in android device
Short answer yes. Android actually forces you to put code that asks for permissions before accessing it. You can find more info here doc . More on reddit.com
🌐 r/androiddev
6
1
February 18, 2022
gps - Check if 'Access to my location' is enabled - Android - Stack Overflow
I have an android app that uses location. But I noticed that if users disable the 'Access to my location' in Settings > Location access, nothing works anymore. How can I check that it's enabled? In... More on stackoverflow.com
🌐 stackoverflow.com
Android: Check if Location Services Enabled using Fused Location Provider - Stack Overflow
But I don´t want to use both Google Play Services fused location provider and old android location. How could I check if the location is enabled by the user using the Fused Location Provider? More on stackoverflow.com
🌐 stackoverflow.com
Android: Checking if google settings location is enabled - Stack Overflow
I'm working on an app that uses google play services. On Some phones, the client returns null for location. This happens because the locaiton option is not enabled on google setting as in the pic More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › how-to-check-if-location-services-are-enabled-in-android-app
How to check if Location Services are enabled in Android App?
July 30, 2019 - GPS_PROVIDER ) ; } catch (Exception e) { e.printStackTrace() ; } try { network_enabled = lm.isProviderEnabled(LocationManager. NETWORK_PROVIDER ) ; } catch (Exception e) { e.printStackTrace() ; } if (!gps_enabled && !network_enabled) { new AlertDialog.Builder(MainActivity.
🌐
Reddit
reddit.com › r/androiddev › check location service is enable or not in android device
r/androiddev on Reddit: check location service is enable or not in android device
February 18, 2022 -

sorry for asking this but i am not a mobile app developer. we are using mobile device management (mdm) to manage android enterprise mobile device but the mdm did not has the feature to enforce location service to enable in settings app.

i would like to ask how developer code their app if the app requires location service to enable in device level before can use the app? is there such coding way to always check if device location service is on or not when the app is launch to use? if location service is off, a pop-up will prompt user to on it and the app will be shutdown if location service is off until user on it?

Edit 1: the location service at device level i referring to is the below (in red):

🌐
TutorialsPoint
tutorialspoint.com › how-to-check-if-location-services-are-enabled-in-android-app-using-kotlin
How to check if Location Services are enabled in Android App using Kotlin?
{ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val button: Button = findViewById(R.id.button) button.setOnClickListener { locationEnabled() if (gpsStatus) { textView.text = "Location Services Is Enabled" } else { textView.text = "Location Services Is Disabled" } } } private fun locationEnabled() { val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } } Step 4 − Add the following code to androidManifest.xml
🌐
YouTube
youtube.com › magic codes
how to check if location is enabled in android device - YouTube
how to check if location is enabled in android deviceIn this video, we learn how to check if location is enabled in android device or not. We write a method ...
Published   May 5, 2022
Views   152
🌐
CodeProject
codeproject.com › Tips › 570208 › Check-whether-location-services-are-enabled-on-And
Check whether location services are enabled on Android Phone - CodeProject
To do this, you have to access to location manager. Location manager has some provider information. For example location services are enabled or disabled. public static boolean control(){ LocationManager locManager = (LocationManager) ...
Find elsewhere
Top answer
1 of 5
38

This android developer training tutorial could help - here's the basics:

Code to run in your Activity onCreate():

 // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mGoogleApiClient.connect();

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

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

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult locationSettingsResult) {

            final Status status = locationSettingsResult.getStatus();
            final LocationSettingsStates LS_state = locationSettingsResult.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(LocationByGPS.this, REQUEST_CHECK_SETTINGS);

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

Override this Method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode) {
        case REQUEST_CHECK_SETTINGS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    GetUserLocation();//FINALLY YOUR OWN METHOD TO GET YOUR USER LOCATION HERE
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to

                    break;
                default:
                    break;
            }
            break;
    }
}

Remember to Implement these in your class:

public class MyClass extends AppCompatActivity implements
    ActivityCompat.OnRequestPermissionsResultCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

  protected static final int REQUEST_CHECK_SETTINGS = 0x1;


  /* 
     your code i.e. with the above code etc....
 */

 }

Good explanation here in this Google developer link.

Cheers!

2 of 5
17

See SettingsApi: check your location request then ensure that the device's system settings are properly configured for the app's location needs.

🌐
Google Support
support.google.com › accounts › answer › 3467281
Manage your Android device’s location settings - Google Account Help
You can use location-based services ... device location is on in settings. ... Some of these steps work only on Android 12 and up. Learn how to check your Android version. You’ll need to touch your device’s screen for some steps. These steps also work on Fitbit Ace LTE. If you have a ...
🌐
Android Developers
developer.android.com › core areas › sensors and location › change location settings
Change location settings | Sensors and location | Android Developers
July 7, 2023 - Rather than directly enabling services such as the device's GPS, your app specifies the required level of accuracy/power consumption and desired update interval, and the device automatically makes the appropriate changes to system settings. These settings are defined by the LocationRequest data object. This lesson shows you how to use the Settings Client to check which settings are enabled, and present the Location Settings dialog for the user to update their settings with a single tap.
🌐
GeeksforGeeks
geeksforgeeks.org › kotlin › how-to-check-gps-is-on-or-off-in-android-programmatically
How to Check GPS is On or Off in Android Programmatically? - GeeksforGeeks
July 23, 2025 - { 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() } } }
🌐
Blogger
keshavpai.blogspot.com › 2018 › 10 › android-check-if-location-is-enabled.html
Android - Check if Location is Enabled
October 12, 2018 - <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> public boolean checkLocation() { LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled = false; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch(Exception ex) {} if(gps_enabled) { return true; } else { return false; } } Android ·
🌐
GitHub
github.com › Richou › react-native-android-location-enabler › issues › 28
Check if location is enabled without opening modal · Issue #28 · Richou/react-native-android-location-enabler
September 19, 2019 - It will be nice to have a function that only checks if the location is turned on instead of asking to turn it on. Useful in case for localize icons such as Google Maps. if GPS is off, localize the show question mark icon.
Author   Richou
🌐
SourceTrail
sourcetrail.com › home › java › solved: how to check if location is enabled android
Solved: how to check if location is enabled android in Java - SourceTrail
December 25, 2023 - Settings.Secure.LOCATION_MODE: This is used to get the current location mode setting. Settings.Secure.LOCATION_PROVIDERS_ALLOWED: Gets the list of allowed location providers. Android has evolved significantly over a decade, and each version comes with its specific features and settings. Hence, the instructive code must factor in the subtle nuances that manifest across different Android versions. The given code comprehensively checks for enabled location across all Android versions, with specific focus on the version KitKat, where the ‘Location Mode’ was introduced.
🌐
Stack Overflow
stackoverflow.com › questions › 50443660 › check-whether-location-service-enabled-from-a-broadcastreceiver-in-android
Check whether Location Service enabled from a BroadcastReceiver in Android - Stack Overflow
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled = false; boolean network_enabled = false; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch(Exception ex) {} try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch(Exception ex) {} if(gps_enabled || network_enabled ){ //Do something.
🌐
Medium
proandroiddev.com › monitoring-gps-and-location-permission-checks-using-livedata-part-1-278907344b77
Monitoring GPS and Location Permission checks using LiveData (Part 1) | by Wahib Ul Haq | ProAndroidDev
November 3, 2018 - In order to make that happen, tracking of driving behaviour through the app was an essential aspect of the project. It means that the app should be able to constantly listen to location coordinates in the background during the user’s journey while driving. We had to implement checks to ensure GPS is enabled on the device and Location Permission is granted by the user.