I have been running a activity with mode = singleInstance in my app. In this activity onStart() method i am initializing a handler like this
Handler handler;
@Override
protected void onStart() { // running handler with post delayed of 5 seconds
handler = new Handler();
handler.postDelayed(() -> {
// doing something
}
}, 5000);
Now sometime when user comes back to my activity from any other app following sequence of Activity life cycle events fires
-> onCreate() // first instance created
-> onStart() // on start of first instance called
-> onCreate() // second instance created
-> onStart() // on start of second instance called
-> onDestroy() // first instance on destroy called
Now handler running twice as onStart() called twice for two different instance created.
I want to stop the handler execution of first instance as it destroyed immidiately after created. I i use handler.removeCallbacksAndMessages(null); it is stopping the second instance handler execution.
How can i make sure that only running activity handler instance executes ?
You should call the removeCallbacksAndMessages function when the activity ends using onDestroy(). This will clean up the handler so that there will only be one running at a time.