Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if GPS is enabled before I try to use it

Tags:

android

gps

I have the following code and it's not good because sometimes GPS takes very long

How can I do the following:

  1. Check if GPS is enabled
  2. Use GPS if it is enabled otherwise use the network provider.
  3. If GPS takes more than 30 seconds, use network.

I can do this with my own logic using a time or Thread.sleep but I think there might be a more stabndard way

// Acquire a reference to the system Location Manager
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

            // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                  // Called when a new location is found by the network location provider.
                    locationCallback(location);
                }

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

                public void onProviderEnabled(String provider) {}

                public void onProviderDisabled(String provider) {}
              };

            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
like image 400
code511788465541441 Avatar asked Oct 14 '13 20:10

code511788465541441


People also ask

How do you ask someone to enable GPS at the launch of an application?

In RESOLUTION_REQUIRED case, we ask user to give permissions, this is where we show the user prompt to enable GPS. Task<LocationSettingsResponse> result = LocationServices. getSettingsClient(getActivity()).

How do I open location settings in android programmatically?

Get current location settingsTask<LocationSettingsResponse> task = client. checkLocationSettings(builder. build()); When the Task completes, your app can check the location settings by looking at the status code from the LocationSettingsResponse object.


1 Answers

There's no standard way, you have to do it on your own with the help of:

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        //Do what you need if enabled...
    }else{
        //Do what you need if not enabled...
    }

And this permission in manifest:

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

As recommendation if GPS is not enabled, usually the standard specifies to popup the Location Settings Activity so the user can specifically enable it...

Hope this helps.

Regards!

like image 68
Martin Cazares Avatar answered Oct 07 '22 11:10

Martin Cazares