To update a user's current location I implement the following method to my project:
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
When the project is executed,The following error will occur:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
And there is an error in the code:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Many solutions have been proposed,Like This and This But not solve any problem.
Please Help To Solve It.
My Code In onCreate Method:
@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);}
And in onMapReady:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
mMap.setTrafficEnabled(true);
mMap.setMyLocationEnabled(true);}
And This:
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);
}
}
Thank You For Any Help :)
Solved my problem because I use splash screen in my project put this code in splash screen activity :
mGoogleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();