我確實需要持續獲取用戶位置;因此,我使用getlastlocation()來獲取用戶的當前位置。但是,它總是返回null。Android google map api getlastlocation()總是返回null
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks
,GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
protected double x, y;
@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();
}
}
protected void onStart(){
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
@Override
public void onConnected(Bundle bundle){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
x = mLastLocation.getLatitude();
y = mLastLocation.getLongitude();
}
else{
Log.e("error", "null");
}
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng gpsLocation = new LatLng(x, y);
mMap.addMarker(new MarkerOptions().position(gpsLocation).title("Here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(gpsLocation));
}
Log.e("error", "null")
總是執行,這意味着getlastlocation()始終返回null。在AndroidManifest,我有足夠的國家批准
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
我搜索了在計算器上類似的帖子,他們給某些原因(例如:GPS不開放),但沒有人可以在我的情況下適用。
你見過,如果你正在進入onConnectionFailed()? – Emmanuel
只需檢查,我沒有輸入onConnectionFailed。 – Hugo