在LocationCallback外,纬度经度为null

时间:2018-08-31 17:18:41

标签: java android location google-play-services

我正在使用Google Play服务api来获取位置。我在LocationCallback中找到了位置,也可以从回调方法内部更新UI。但是,当我想将lat,lng存储到另一个变量中时,它变为0。这是我的代码,这里我缺少什么?

FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
LocationRequest request = new LocationRequest();
request.setInterval(5000);
request.setFastestInterval(2500);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationCallback callback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        for (Location location : locationResult.getLocations()) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();

            lattitude = lat;
            longitude = lng;

            ((TextView) findViewById(R.id.tvLat)).setText(String.valueOf(lat));
            ((TextView) findViewById(R.id.tvLng)).setText(String.valueOf(lng));
        }
    }
};

client.requestLocationUpdates(request, callback, null);

0 个答案:

没有答案