如何获得粗略位置使用WiFi或GSM或GPS,取其可用?如何获得、取其、位置、WiFi

2023-09-05 09:26:13 作者:╰记忆的沉淀落满尘埃

在启动我的应用程序只需要一个粗定位服务。

My app only needs a coarse location service when started up.

在细节,我需要应用程序的大致位置,从而为用户提供附近的店铺信息。

In detail, I need the app's rough location so as to provide the users with the shop info nearby.

的位置并不需要不断更新。此外,粗略定位将足以在这种情况下

The location does NOT need to be updated constantly. In addition, coarse localization will be sufficient in this case.

我希望应用程序自动选择GSM,或WiFi或GPS,取其可用。

定位服务也应该是一次性节省电话能源

我怎么可以这样做呢?

我单独使用GPS都试过了。

I have tried using GPS separately.

我的问题是我不知道如何阻止全球定位系统的不断刷新,位置功能。我不知道如何使手机选择一个出了三种方法,无论是。

My problem is I don't know how to stop the constantly-refreshing-location feature of GPS. I don't know how to make the phone select one out of the three methods, either.

有些样品codeS或想法都大大AP preciated。

Some sample codes or ideas are greatly appreciated.

推荐答案

下面是一个特定的观点:

Here's a certain point of view:

private void _getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) 
            getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}

这可能不过要求FINE_LOCATION访问。所以:

This might however request a FINE_LOCATION access. So:

另一种方式是使用此的,它使用的LocationManager.

Another way is to use this which uses the LocationManager.

最快的方式是使用最后一个已知的位置,这一点,我用它和它的相当快:

The quickest possible way is to use the Last Known location with this, I used it and it's quite fast:

private double[] getGPS() {
 LocationManager lm = (LocationManager) getSystemService(
  Context.LOCATION_SERVICE);
 List<String> providers = lm.getProviders(true);

 Location l = null;

 for (int i=providers.size()-1; i>=0; i--) {
  l = lm.getLastKnownLocation(providers.get(i));
  if (l != null) break;
 }

 double[] gps = new double[2];
 if (l != null) {
  gps[0] = l.getLatitude();
  gps[1] = l.getLongitude();
 }

 return gps;
}