Android Handler for repeated task – will it overlap ? Timer-task VS handler VS alarm-manager

You can extend Application class and do your work in it.

public class App extends Application {

    private Handler handler;

    @Override
    protected void onCreate() {
        super.onCreate();
        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
        }
    };
}

And declare your class in manifest:

<application android:name=".App">

Edited

But it will work only if your app is running, otherwise you can use AlarmManager.

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.

  1. Timer-task -> runs while application is alive. best for short term timing. Resource usage is higher.

  2. 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.

  3. Alarm-manager -> The best way to schedule something to happen in future even if the app is killed. (this is what I should apply for my app).

This is what I figured out. Correct me if I’m wrong.

Leave a Comment