I'm trying to build an Android app which will repeatedly run some process every 10 mins.
As I found out Handlers
are more reliable than timers or scheduling. So I'm going to develop my app using the Handlers
using the given below codes.
I'm little bit concerned that the below codes will create separate Handlers
at each time I start the app and keep them running parallel, may be since I'm creating the Handler
on onCreate
.
So what is the best way to keep only a single Handler
runs in background at a time?
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler(); // new handler
handler.postDelayed(runnable, 1000*60*10); // 10 mins int.
setContentView(R.layout.activity_pro__sms);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* my set of codes for repeated work */
foobar();
handler.postDelayed(this, 1000*60*10); // reschedule the handler
}
};
I decided to answer my own question since I've found out how to do it right way. The Android way. First of all what I was trying to do and posted in the question is a wrong approach to my requirement. Now I'm posting this so someone else will not do it wrong way but the following way.
Android has few options for timing.
Timer-task -> runs while application is alive. best for short term timing. Resource usage is higher.
Handler -> runs while application is alive. But not suitable to used as a scheduler. (this is what I've asked and it's not the correct way to do that). Handlers
are the best way to do something repeatedly till the app is killed.
This is what I figured out. Correct me if I'm wrong.