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

泄露秘密 提交于 2019-12-04 17:48:34

问题


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

回答1:


Just using this, you can check GPS availability

    LocationManager mlocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);;
    boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);



回答2:


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!




回答3:


Think you could use the code in my answer to: Location servise GPS Force closed

It gives you a callback method for GPS first fix and location changes that can be very convenient. This also makes it easy to change the implementation of GPSTracker to switch to network if GPS takes too long to get a first fix.



来源:https://stackoverflow.com/questions/19368818/how-can-i-check-if-gps-is-enabled-before-i-try-to-use-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!