为什么这个双重空?

时间:2016-02-28 23:40:55

标签: java android algorithm performance google-maps

我在服务中,我只需要经度和纬度。只有两个双打。所以,我做了以下几点:

LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
}

由于某种原因,纬度和纬度为空。文档说如果位置信息不可用,但它应该可用,这是可能的,因为我首先检查if语句中是否有权限,对吧?在我正在测试的手机中,我确实启用了位置。 为什么纬度和经度为空?

3 个答案:

答案 0 :(得分:0)

原因是,您正在检查上一个已知位置,如果此提供程序之前没有提供任何位置,则所有相应参数将为null。方法getLastKnownLocation重用其他应用程序/服务提取的信息,并且可能发生没有保存信息的情况。

您可以尝试使用方法requestSingleUpdate进行单一位置更新,这样您就不会依赖于您的设备状态。

答案 1 :(得分:0)

这是因为,即使启用了位置,也没有“lastKnownLocation”可用。如果您去(例如)谷歌地图应用程序并询问当前位置,在成功获取位置后,转到您的应用程序,它将工作(lat和lon!= null)。

编辑:我不知道Android位置服务API的代码,但对于谷歌地图API就是这样的(我肯定是类似的):

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.code == 'Delete') {
        console.log('The physical key pressed was the DELETE key');
    }
    if (event.code == 'Backspace') {
        console.log('The physical key pressed was the BACKSPACE key');
    } 
    if (event.key == 'Delete') {
        console.log('The keypress meant the same as pressing DELETE');
        // This can happen for one of two reasons:
        // 1. The user pressed the DELETE key
        // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
        //    FN+BACKSPACE deletes the character in front of the text cursor,
        //    instead of the one behind it.
    }
    if (event.key == 'Backspace') {
        console.log('The keypress meant the same as pressing BACKSPACE');
    }
});

答案 2 :(得分:0)

如果您尝试这样做,输出是什么? locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);