如何使用 Wifi 或 GS​​M 或 GPS(以可用者为准)获取粗略位置? [英] How to get the coarse location using Wifi or GSM or GPS, whichever is available?

查看:33
本文介绍了如何使用 Wifi 或 GS​​M 或 GPS(以可用者为准)获取粗略位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用在启动时只需要一个粗略的位置服务.

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.

我的问题是我不知道如何停止 GPS 的不断刷新位置功能.我也不知道怎么让手机从三种方法中选择一种.

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.

非常感谢一些示例代码或想法.

Some sample codes or ideas are greatly appreciated.

推荐答案

以下是某个观点:

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:

另一种方法是使用 this 它使用 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;
}

这篇关于如何使用 Wifi 或 GS​​M 或 GPS(以可用者为准)获取粗略位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆