One of my class has two handlers to send messages at regular interval of time. This class is instantiated in one of the activities. Below is the code:
public class MyClass {
private Boolean started = false;
private Handler handler1 = new Handler();
private Handler handler2 = new Handler();
private Runnable runnable1 = new Runnable() {
@Override
public void run() {
sendMessage("blah");
}
};
private Runnable runnable2 = new Runnable() {
@Override
public void run() {
sendMessage("blah blah");
if (started) {
triggerMessageSending();
}
}
};
}
public void startMessageSending(){
triggerMessageSending();
}
private void triggerMessageSending(){
started = true;
handler1.postDelayed(runnable1, 500);
handler2.postDelayed(runnable2, 1000);
}
public void stopMessageSending(){
started = false;
handler1.removeCallbacks(runnable1);
handler2.removeCallbacks(runnable2);
}
}
Here is my activity:
public class MyActivity extends Activity {
private MyClass myClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myClass = new MyClass();
myClass.startMessageSending();
}
@Override
protected void onStop() {
super.onStop();
myClass.stopMessageSending();
}
}
Everything works fine for the first time. If I press back button and go to the previous activity and come back again(without exiting the app), the sendMessage method is called twice. This becomes three if I do it again. It calls the method as many times as I start this activity without exiting the app. If I exit the app and do this again, it works fine for the first time.
What is the reason for this? Where am I wrong?