更新用户的当前位置 我在我的项目中实现了以下方法:
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
项目执行时,会出现如下错误:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
代码中有一个错误:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
提出了很多方案,赞This和 This 但没有解决任何问题。
请帮忙解决
我在 onCreate 方法中的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
FirebaseCrash.report(new Exception("Exceptin"));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mGoogleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(60*1000)
.setFastestInterval(1*1000);}
在 onMapReady 中:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
mMap.setTrafficEnabled(true);
mMap.setMyLocationEnabled(true);}
还有这个:
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mLastLocation = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mLastLocation
|| mLastLocation.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mLastLocation.getTime() < System.currentTimeMillis() - TWO_MIN) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
// Schedule a runnable to unregister location listeners
Executors.newScheduledThreadPool(1).schedule(new Runnable() {
@Override
public void run() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);//This Line Return Error
}
}, ONE_MIN, TimeUnit.MILLISECONDS);
}
}else{
handleNewLocation(mLastLocation);
}
}
感谢您的帮助:)
最佳答案
解决了我的问题,因为我在我的项目中使用了闪屏,将这段代码放在闪屏 Activity 中:
mGoogleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
关于Android:GoogleApiClient 尚未连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631134/