I want to be able to toggle a MyLocationNewOverlay on and off. My current code is:-
void btnTrack() {
btnTrack = (Button) findViewById(R.id.btnStart);
btnTrack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String btnText = btnTrack.getText().toString();
GpsMyLocationProvider provider = new GpsMyLocationProvider(ctx);
provider.addLocationSource(LocationManager.NETWORK_PROVIDER);
// My Location Overlay
MyLocationNewOverlay mysLocationoverlay = new MyLocationNewOverlay(provider, map);
if (btnText.equalsIgnoreCase("Start")) {
/**************************************************************************
* Get and display the current location
**************************************************************************/
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mysLocationoverlay.enableMyLocation(); // not on by default
mysLocationoverlay.setDirectionArrow(BitmapFactory.decodeResource(getResources(),
R.drawable.marker_node), BitmapFactory.decodeResource(getResources(), R.drawable.marker_poi_default));
mysLocationoverlay.runOnFirstFix(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
btnTrack.setText("CANCEL");
}
});
}
});
map.getOverlays().add(mysLocationoverlay);
}
else {
mysLocationoverlay.disableMyLocation();
mysLocationoverlay.disableFollowLocation();
map.getOverlays().remove(mysLocationoverlay);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
btnTrack.setText("START");
}
}
});
}
I'm pretty sure that the problem is with the runnable but I can't see any way of terminating that when I toggle the button to 'Cancel'led.
I'm using osmdroid v6.1.0 and osmbonuspack v6.6.0
How can I stop the runnable?
You are creating a local instance of MyLocationNewOverlay every time the button is clicked.
When the button is clicked for the first time a MyLocationNewOverlay instance is created, activated and added to the map view.
When the button is clicked for the second time, another new instance of MyLocationOverlay is created. This new instance is deactivated and removed from map view - well, not really, since it was never activated nor added.
I would suggest to keep a reference to the MyLocationOverlay instance in your activity (or fragament, denpends on your situation) and create it only the first time the button is clicked (check for null).