android – 如何获取设备位置

所以,我正在尝试为练习构建一个天气应用程序,我一直在试图找到位置的问题.我读过人们建议通过融合位置API使用getLastLocation,问题是如果他们还没有在设备上注册的位置它出现null.我注意到使用模拟器的时间很少见,但我仍然喜欢我的应用程序来正确处理它.您可能碰到的一个例子是,他们只是关闭并重新打开GPS,或者手机刚打开.我做的一件事是如果getLastLocation确实返回null,是请求更新,但是你仍然需要等待设备注册更新的位置,这与天气应用程序的所有数据都是基于你的’你’仍然有点遇到同样的问题.我注意到其他应用程序这不是问题,有时我实际上必须加载谷歌地图才能让它注册一个位置. Google地图如何强制它更新位置?这是我的getLocation方法的示例:

public void getLocation() throws SecurityException {
    boolean gps_enabled;
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (gps_enabled) {

        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location != null) {
            startGetForecast(location);
        } else {
            LocationRequest request = LocationRequest.create();
            request.setNumUpdates(1);
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, this);
        }
    } 
    else {
        AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
        alertDialogFragment.setErrorTexts("Location Unavailable", "Could not retrieve location information.", "Exit");
        alertDialogFragment.show(getSupportFragmentManager(), "Location Unavailable");
    }
}

最佳答案 注意:这个答案可能听起来像没有直接回答问题,但在与OP聊天(有问题的评论)后,因为他的代码一般都没问题,但问题是这个问题,这个答案已经满足了OP.

Fortunately, the standard library Is not the only way Google can get
code into your hands. In addition to the standard library, Google
provider Play services. This is a set of common services that are
installed alongside the Google Play store application. To fix this
location mess, Google shipped a new locations services in Play
Services called the Fused Location Provider.

Since these libraries
live in another application, you must actually have that application
installed. This means that only devices with the Play Store app
installed and up to date will be able to use your application.

所以结论是:

>您需要如上所述在设备上测试应用程序.
>由于您使用的是融合位置提供程序Api,这意味着Api将自动确定以下某个来源的最后位置:

> GPS收音机
>细胞塔的粗糙点
> WiFi连接

>因此,您可以轻松地从代码中移除GPS条件
>如果您必须使用GPS信号,那么您需要远离建筑物,实验室,家庭或办公室.

如果你想在上述资源中挖掘更多,并且有很多在线资源.

资源:答案的第一部分,它的来源是:

Android编程:Google Play服务下的Big Nerd Ranch Guide第2版第31章第552页

点赞