-6

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();
    }
mattm
  • 5,851
  • 11
  • 47
  • 77
Raees Khan
  • 371
  • 1
  • 5
  • 20

2 Answers2

1

The mGoogleApiClient.connect() function is asynchronous. You have to wait until onConnected until the last location is available. There is a clear example of this in the documentation.

mattm
  • 5,851
  • 11
  • 47
  • 77
1

Add this code to your onConnected, thats where it would get Last Known Location.

private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
private static Context context;

// added
private LocationRequest mLocationRequest; 
private Double latitude;
private Double longitude;
private String TAG = ""; // set your TAG

@Override
public void onConnected(Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startLocationUpdates();
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if(mLastLocation == null){
        startLocationUpdates();
    }

    if (mLastLocation != null) {
        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();

        // set your tag
        Log.d(TAG, String.valueOf(latitude));
        Log.d(TAG, String.valueOf(longitude));

    } else {
        Toast.makeText(context, "Location not Detected, Did you turn off your location?", Toast.LENGTH_SHORT).show();
    }
}

protected void startLocationUpdates() {
    // Create the location request
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(30 * 1000)
            .setFastestInterval(5 * 1000);

    // Request location updates
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

And remove synchronized from your method, Just make it public. Something like this below:

public void buildGoogleApiClient() { }
Tosin Onikute
  • 3,883
  • 6
  • 38
  • 61