Reputation: 313
I have used ToggleButton in my MAINACTIVITY.java. When it is on am fetching the current location from another class GPSLOCATION.java and updating to server.
<ToggleButton
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:onClick="onToggleClicked" />
public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
update_alert();
} else {
timerAlert.cancel();
}
}
But since its run by using TimerTask i.e., If TOGGLEBUTTON is ON then for every one minute LOCATION is fetched and updated in server. Instead I want to get the state of TOGGLEBUTTON in the GPSLOCATION.java under onLocationChanged method and if ON then I need to update it to server, I know it is possible can anyone help me to get rid of this scenario.
Upvotes: 0
Views: 371
Reputation: 451
So you want to get the current state of this button in another class?
Could you possibly use the EventBus
?
See: http://square.github.io/otto/
You could fire off an Event
when the switch is toggled, and then @Subscribe
to the event in the class you want to handle the updating to the server.
For example:
Register both of your classes with the EventBus (assuming you initialise the EventBus at application level) you can call this in onCreate
:
MyApplication.getInstance().getBus().register(this);
Or something along the lines, this will register the desired class to receive or be able to post events along the bus.
Make sure to do this in both classes!
Then you must create an event to be posted, something like:
public class ToggleEvent {
public ToggleEvent() {
//
}
}
And then Post the event when onToggled
is called like so:
MyApplication.getInstance().getBus().post(new ToggleEvent());
Then in your GPSLocation
class you can have a method like:
@Subscribe public void retrieveToggleEvent(ToggleEvent event) {...}
This will retrieve the event when it's triggered (i.e. when onToggle
is called and the event is fired!). Then you should be able to post to the server in retrieveToggleEvent
.
You can also pass useful data along the Bus by using simple getter
methods. In your case it might be better to override onToggled
then you can pass through the boolean state of the switch in the bus, and handle whether its true/false in your @Subscribe
method of GPSLocation
.
Since registering a bus in a class will stay in memory forever, you should think about unregistering the bus onDestroy
:
MyApplication.getInstance().getBus().unregister(this);
Hope this helps!
Upvotes: 1