onLocationChanged is never called on Android

onLocationChanged is never called on Android

I had problems with this while developing #BresTram.

I was developing a new feature, allowing my users to find bus stops nearby using their GPS location.

But whatever I was trying, my location was never set, and onLocationChanged was never called.

Here is what my Activity would look like :

public class DisplayGPSInfoActivity extends BaseActivity implements LocationListener {
private static final String TAG = "DisplayGPSInfoActivity";

private ViewFlipper vf;

private LocationManager locationManager;
private String provider;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Initiating ViewFlipper
setContentView(R.layout.activity_display_gpsinfo_request);
vf = (ViewFlipper) findViewById(R.id.viewFlipper);

this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

//Choosing the best criteria depending on what is available.
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
//provider = LocationManager.GPS_PROVIDER; // We want to use the GPS

// Initialize the location fields
Location location = locationManager.getLastKnownLocation(provider);
}

@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "GPS LocationChanged");
double lat = location.getLatitude();
double lng = location.getLongitude();
Log.d(TAG, "Received GPS request for " + String.valueOf(lat) + "," + String.valueOf(lng) + " , ready to rumble!");

// Do clever stuff here
}
}

You can forget about the ViewFlipper, that is here only to show something to the user.
Basically, I am letting android decide which provider he wants to use (GPS or Network), and request for the last known location.
Then, I want to do something clever each time onLocationChanged is called.

Problem is, it is not. never. Ever. . .

After having verified hundred times that I had

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

correctly defined in my manifest, and that yes, other GPS based apps were working fine on my phone; I finally found the solution.

As stupid as it seems, I had forgotten to request the updates. . .
Something like that would do the job :


@Override
 protected void onResume() {
super.onResume();
Log.v(TAG, "Resuming");
locationManager.requestLocationUpdates(provider, 400, 1, this);
 }

I was somehow expecting that is was automatic, implied by the fact that my activity implements LocationListener.

Well it is not.
So, if any of you has the same problem, look whether you actually ask for something before getting angry because you don't receive it :D.

Have fun hacking around.
Oh, and if you leave in Brest, give a shot to #BresTram; it is awesome!