I am using Fused Location to get current location of my device, but the code that I have implemented always return NULL. I have double checked that my device Location is ON and is set to High Accuracy Mode. Please tell what is problem in my code?
My Code:
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
public class FusedLocationTest implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
private static Context context;
public Location getCurrentLocation(Context context) {
this.context = context;
buildGoogleApiClient();
mGoogleApiClient.connect();
if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
return mLastLocation;
}
/*connect to fused location provider*/
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
@Override
public void onConnectionSuspended(int i) {
}
}
Call on button Click:
@Override
public void onClick(View v) {
Location l = new FusedLocationTest().getCurrentLocation(this);
if(l!=null)
Toast.makeText(this,l.getLatitude()+", "+l.getLongitude(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"NULL LOCATION", Toast.LENGTH_LONG).show();
}