2016-02-29 27 views
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檢查它一直沒有連接

+1

不要嘗試調用'getLastLocation()''直到onConnected()'被調用時,不可能很快。 – CommonsWare

+0

這是行不通的,但它根本不準確,任何建議? – JenuRudan

+0

那麼,你似乎只有粗略的位置權限。它應該是不準確的。此外,'getLastKnownLocation()'不會在質量方面指定任何內容,因此它可能特別使用低功耗方法。 – CommonsWare

回答

2

你需要一個聽衆註冊的位置的事件,並開始監聽短時間連接時時間到幾個地點收到,並比較其準確性,來源等,以確定哪一個是最好的,並使用那一個。

閱讀Location strategies谷歌文檔,這是非常有用的,並有代碼示例,你需要做什麼,以獲得準確的位置。

而且此權限添加到清單:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>