Y. Franco
Y. Franco

Reputation: 357

Using Handler or Thread with while true?

I am wondered what should I use if I want a task to happen every five seconds when a flag is true. I am running it on an andrid device, so the performance is important.

Option one is with an Handler:

public void handleLocation() {
    handler.postDelayed(new Runnable() {
        public void run() {
            Toast.makeText(mContext, "Five Seconds", Toast.LENGTH_SHORT).show();          // this method will contain your almost-finished HTTP calls
            if (currentLocation != null && isWorking) {
                setMockLocation(currentLocation);
                setMockLocation2(currentLocation);
            }
            handler.postDelayed(this, FIVE_SECONDS);
        }
    }, FIVE_SECONDS);
}

Second option is with a Thread:

 public void run() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    if (isWorking) {
                        if (currentLocation != null)
                            setMockLocation(currentLocation);
                        setMockLocation2(currentLocation);
                    }
                    sleep(5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Toast.makeText(mContext, mContext.getString(R.string.err0_unknown), Toast.LENGTH_LONG).show();
            }
        }
    };

    thread.start();
}

What do you prefer to use? Is there a better solution?

Upvotes: 2

Views: 885

Answers (1)

weston
weston

Reputation: 54791

There should be no one option to prefer, rather know the differences and choose the option that best fits the specific scenario.

postDelayed

In this case the code will run on the same thread the handler is attached to.

If this is your main (UI) thread then make sure you do not do long running tasks with this method.

This also means you cannot guarantee the task will run precisely every 5 seconds. If the handlers thread is busy, your task will have to wait.

new Thread

In the second case, a new thread will be spun up just to deal with this task. This is only suitable for consideration in my view when the thread will have the same lifetime as the application and will be frequently busy. Otherwise I would use a message as in first or a third option you have not listed:

AsyncTask

It has great support for updating the UI after the task has run.

Async tasks run on a shared thread by default, but you can execute on a thread pool thread:

new YourAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

IntentService

Another alternative to running a dedicated thread is to start a service. This has it's own lifecycle and isn't affected by UI lifecycle like an async task would be.

TimerTask

This is available but has no advantage I know of over the postDelayed techinique.

Upvotes: 1

Related Questions