来自Google Play服务的位置更新不起作用

时间:2019-06-30 18:10:20

标签: location google-play-services

下面有一些代码。由于字段latLng未按位置更新,因此无法正常工作。你知道为什么吗 ?在应用程序运行时,此字段的值始终为Text1。

我不知道如何解决这个错误。

永远不会调用方法onLocationResult。

下面有一些代码。由于字段latLng未按位置更新,因此无法正常工作。你知道为什么吗 ?在应用程序运行时,此字段的值始终为Text1。

我不知道如何解决这个错误。

private FusedLocationProviderClient fusedLocationClient;
private LocationCallback locationCallback;
private LocationRequest locationRequest;

protected void createLocationRequest() {
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    createLocationRequest();





    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            TextView latLng = findViewById(R.id.latLng);
            if (locationResult == null) {
                latLng.setText(Long.toString(Calendar.getInstance().getTimeInMillis()));
                return;
            }
            for (Location location : locationResult.getLocations()) {

                latLng.setText(String.valueOf(location.getLatitude()));
            }
        }


    };
}

@Override
public void onStart() {
    super.onStart();

    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        TextView latLng = findViewById(R.id.latLng);
                        latLng.setText(String.valueOf(location.getLatitude()));
                    }
                }
            });
}


private void startLocationUpdates() {
    fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null /* Looper */);
}




@Override
protected void onResume() {
    super.onResume();

        startLocationUpdates();

    }

}

0 个答案:

没有答案