FusedLocationApi.requestLocationUpdates - onLocationChanged is not getting called

1k views Asked by At

I've been trying to get the current location of the device (not constant update) in my android app throughout the whole day. I was using GoogleApiClient. As the location always returned null - I read that using FusedLocationApi.requestLocationUpdates might fix it. So I did that.

Now it's not working too. Here's my code. How could I fix this?

    package com.example.root.restaurant;
    import android.Manifest;
    import android.annotation.TargetApi;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Build;
    import android.provider.ContactsContract;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.annotation.RequiresApi;
    import android.support.v4.app.ActivityCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.RelativeLayout;
    import android.widget.Button;
    import android.graphics.Color;
    import android.widget.EditText;
    import android.view.View;
    import android.widget.TextView;
    import android.content.Intent;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.FusedLocationProviderApi;
    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.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;

    import org.w3c.dom.Text;

    import java.util.List;

    public class MainActivity extends AppCompatActivity implements         GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

        private static GoogleApiClient googleApiClient;
        private Location mLastLocation;
        TextView t;
        private Double myLatitude;
        private Double myLongitude;
        private LocationRequest locationRequest;
        private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i("jennysMsg", "..............................Started");

    t = (TextView) findViewById(R.id.textView2);

    locationRequest = new LocationRequest();
    locationRequest.setInterval(15 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setSmallestDisplacement(0);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .setAccountName("kfoozminus")
            .build();
    if (googleApiClient != null) {
        Log.i("jennysMsg", ".....................................it's not nul!!!");
        googleApiClient.connect();
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if (location == null) {
        requestLocationUpdates();
    }
    else {
        myLatitude = location.getLatitude();
        myLongitude = location.getLongitude();
        t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude));
    }
}

private void requestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {

    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
    t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude));

}

@Override
protected void onStart() {
    super.onStart();
    //googleApiClient.connect();
}

@Override
protected void onResume() {
    super.onResume();
    if(googleApiClient.isConnected()) {
        requestLocationUpdates();
    }
}

@Override
protected void onPause() {
    super.onResume();
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

@Override
protected void onStop() {
    super.onStop();
    googleApiClient.disconnect();
}
    }
1

There are 1 answers

1
teck wei On

First of all you need to check wether you add permission in your manifest.Either ACCESS_COARSE_LOCATION if you want approximate location or ACCESS_FINE_LOCATION for precise location.

Second you code seem fine for me except you need to uncomment the googleApiClient.connect() from your onStart method.

If you using emulator it couldn't return location to you but instead you need to create custom location(longitude,latitude) just beside the emulator click the setting/more icon you will be able to find longitude and latitude and set the longtitude and latitude manually and click send, you should be good to go. If you still not working you can either try to restart your emulator or please use a real device to test out this code.

Updated: Please check wether your emulator include google package, if you didn't include google package while you try to access google play servide it will always return null in your google play-service