My activity sometimes crashes when it goes out of view. It uses a LocationListener
to receive location updates and show them on the screen. Here is the relevant code.
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
tv = (TextView) findViewById(R.id.textView1);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
@Override
protected void onStop() {
lm.removeUpdates(listener);
tv = null;
lm = null;
super.onStop();
}
private LocationManager lm;
private TextView tv;
private final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
tv.setText(location.getLatitude() + ", " + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
}
onLocationChanged()
often gets called while tv
is null
, promptly causing a NullPointerException
. I'm not setting tv
to null
anywhere other than onStop()
, and the activity's mStopped
is true
according to the debugger. I suspect there's a race condition where location messages get enqueued on the main thread's Handler
right as the activity is being stopped.
This behavior doesn't seem to be documented anywhere. How do I prevent onLocationChanged()
from being called after onStop()
?