0
我想在地圖的活動,以紀念當前用戶的位置,但LocationServices.FusedLocationApi.getLastLocation的召喚總是返回nullLocationServices.FusedLocationApi.getLastLocation總是得到空
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
protected void onStart() {
if(mGoogleApiClient.isConnected())
Toast.makeText(this,"Client Connect",Toast.LENGTH_SHORT).show();
else
mGoogleApiClient.connect();
super.onStart();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
LatLng myLocation = null;
if(mLastLocation!=null) {
myLocation = new LatLng(mLastLocation.getLatitude(),
mLastLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
mMap.getMaxZoomLevel() - 5));
}
} else {
// Show rationale and request permission.
}
}
}
此外,我已經添加的權限清單文件
爲mGoogleApiClient檢查它一直沒有連接
不要嘗試調用'getLastLocation()''直到onConnected()'被調用時,不可能很快。 – CommonsWare
這是行不通的,但它根本不準確,任何建議? – JenuRudan
那麼,你似乎只有粗略的位置權限。它應該是不準確的。此外,'getLastKnownLocation()'不會在質量方面指定任何內容,因此它可能特別使用低功耗方法。 – CommonsWare