如何在尝试使用GPS之前检查其是否已启用

12

我有以下代码,但其中存在问题,因为有时GPS定位需要很长时间。

我该如何做到以下几点:

  1. 检查GPS是否已启用
  2. 如果GPS已启用,则使用GPS;否则使用网络提供程序。
  3. 如果GPS耗时超过30秒,则使用网络。

我可以使用自己的逻辑来完成此操作,例如使用time或Thread.sleep,但我认为可能有更标准的方法。

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

再考虑一下你的第三个条件。将其提高到60秒。30秒通常只适用于使用互联网的AGPS。 - AlexWien
3个回答

11

没有标准的方法来完成这个任务,你需要自己动手,并寻求以下帮助:

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

还需要在清单文件中添加以下权限:

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

如果GPS未启用,建议弹出“位置设置”活动页面,以便用户可以特定地启用它...

希望这可以帮到您。

祝好!


1
此外,为了按照这个答案所示的方式进行调用,您需要将以下内容添加到您的AndroidManifest.xml文件中:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>。 - bsara

10

只需使用这段代码,您就可以检查GPS的可用性:

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

1

我在回答中的代码是否可用于解决“位置服务GPS强制关闭”的问题?

该代码提供了一个回调方法,用于获取GPS第一次定位和位置变化,非常方便。这也使得很容易修改GPSTracker的实现,以便在GPS获取第一次定位时间过长时切换到网络定位。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接