Prithniraj Nicyone Prithniraj Nicyone - 5 months ago 146
Android Question

How to start handler again after calling removeCallbacks or removeCallbacksAndMessages on handler in android

I am working on an android app and have a

Fragment
in which I send an API request each 60 seconds. I am using a
Handler
in this
Fragment
to perform this work in the following manner :

// Global Variable in Fragment
private boolean isHandlerStopped = false;

// Create the Handler object (on the main thread by default) Handler handler = new Handler();

// Define the task to be run here
private Runnable runnableCode = new Runnable() {
@Override
public void run() {

if(!isHandlerStopped){

// Get the No of New Feeds
functiontoCall();

// Repeat this runnable code again every 60 seconds
handler.postDelayed(runnableCode, 60000);
}
}
};
handler.post(runnableCode);


Now I have some links in this fragment which will open some activity in app and in that activity this fragment will be loaded again.
When I load this fragment in some other activity, I need to remove the callbacks from this handler as I do not want to send request to API in this case.
So, I have checked the condition and used the below code to stop callBacks.

isHandlerStopped = true;
handler.removeCallbacksAndMessages(runnableCode);


and in
onPause
function I have written the below line :

handler.removeCallbacks(runnableCode);


Now when I come back to my fragment again, the handler does not work and If I remove removeCallbacks from onPause function and it works fine.

But I cannot remove
removeCallbacks
method from
onPause
function, how can I start the handler again with this.

Please help me if anyone know how to do this.

Thanks a lot in advanced.

Answer

Override onResume as well and restart your Handler there.

@Override
protected void onResume() {
    super.onResume();
    handler.post(runnableCode);
}
Comments