Reputation: 920
I have been developing iOS apps for quite a time and now i have switched to android. I have a requirement in which I have to start timer(In think in Android, I need to use handler) when view appears(onResume) and invalidate timer(stop handler) when view disappears(onPause). I am able to create runnable Handler but not able to stop it. My code is:
protected void AutoRefresh() {
try{
handler.postDelayed(new Runnable() {
public void run() {
new LongOperation().execute("");
}
AutoRefresh();
}, 60000);
}
catch(Exception ex){
}
}
Now, how can I stop this this handler thread when view disappears. Please also comment, if its not the right way to do timer implementation in android.
Upvotes: 2
Views: 590
Reputation: 87064
when view appears(onResume) and invalidate timer(stop handler) when view disappears(onPause). I am able to create runnable Handler but not able to stop it.
Keep a reference to the Runnable
you use:
private Runnable mRefresh = new Runnable() {
public void run() {
new LongOperation().execute("");
}
AutoRefresh();
}
//...
protected void AutoRefresh() {
handler.postDelayed(mRefresh, 60000);
}
and in onPause
remove it like this:
handler.removeCallbacks(mRefresh);
Keep in mind that this will not remove the currently Runnable
that is being executed(if any) so in the LongOperation
's onPostExecute
method you might want to check if the Activity
is still available before refreshing the UI or doing any other interaction with the Activity
.
Please also comment, if its not the right way to do timer implementation in android.
You seem to need to do an action at a certain interval of time and using a Handler
is the way to do it, I don't think a timer is what you need.
Upvotes: 2