Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
};
like image 861
kuma DK Avatar asked Oct 04 '14 07:10

kuma DK


People also ask

What is the difference between Android timer and a handler to do action every n seconds?

Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).

Why do we use handler in Android Studio?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .


1 Answers

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.

like image 56
Bracadabra Avatar answered Oct 10 '22 04:10

Bracadabra