这就是您需要的代码:
protected LocationCallback mLocationCallback = new LocationCallback()
{
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
super.onLocationAvailability(locationAvailability);
if(!locationAvailability.isLocationAvailable())
{// No location available
checkLocationSettings();
Snackbar snackLocationUnavailable = Snackbar.make(findViewById(R.id.myCoordinatorLayout), R.string.location_unavailable, Snackbar.LENGTH_LONG);
snackLocationUnavailable.show();
}
else
{
Snackbar snackLocationAvailable = Snackbar.make(findViewById(R.id.myCoordinatorLayout), R.string.location_available, Snackbar.LENGTH_LONG);
snackLocationAvailable.show();
}
}
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mLastLocation = locationResult.getLastLocation();
mMyLatLng = new LatLng(valueOf(mLastLocation.getLatitude()), valueOf(mLastLocation.getLongitude()));
meMarker.setPosition(mMyLatLng);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mMyLatLng, 15));
Snackbar snak2 = Snackbar.make(findViewById(R.id.myCoordinatorLayout), R.string.location_updated, Snackbar.LENGTH_INDEFINITE);
snak2.show();
}
};
...
onCreate(){
// Build GoogleApiClient
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//`Build LocationRequest
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(2000) // 2 seconds, in milliseconds
.setFastestInterval(1000); // 1 second, in milliseconds
`
//
Build LocationSettingsRequest
LocationSettingsRequest.Builder lRbuilder = new LocationSettingsRequest.Builder();
lRbuilder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = lRbuilder.build();
lRbuilder.setAlwaysShow(true);
// ...
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationCallback, null);
//...
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationCallback);