2016-02-29 29 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"/>