I am getting current location using Location Services api. Actually, I have verified whether location is enabled or not using Location Manager class in onResume() method and if is not enable then sending user to Location Setting using intent. After enabling location coming back to activity and trying to connect Google client api. But it is not connecting and not giving any location. I have used this code.
protected synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(connectionCallbackListener)
.addOnConnectionFailedListener(connectionFailedListener)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onResume() {
super.onResume();
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("Location is disabled")
.setMessage("Please enable your location")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
Log.v("Connection Status", String.valueOf(mGoogleApiClient.isConnected()));
mGoogleApiClient.connect();
}
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
GoogleApiClient.ConnectionCallbacks connectionCallbackListener = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null){
Log.v("Latitude", String.valueOf(mLastLocation.getLatitude()));
Log.v("LOngitude", String.valueOf(mLastLocation.getLongitude()));
startIntentService();
}
}
@Override
public void onConnectionSuspended(int i) {
}
};
GoogleApiClient.OnConnectionFailedListener connectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i("Connection failed", String.valueOf(connectionResult.getErrorCode()));
}
};
And I am calling buildGoogleApiClient() method in onCreate() callback. Please someone tell me solution as it is very important.