Roman
Roman

Reputation: 4513

How does TimerTask on Android manages threads?

I was wondering how the TimerTask is working with threads.

For example, I've got a code that executes a TimerTask, which has a 'run' method which will run on the UI Thread.

class looper extends TimerTask {

    public looper() {

    }

    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timer.schedule(new looper(), new Date(new Date().getTime() + 100));
            }
        });
    }
}

and the timer would start like this:

    timer = new Timer();
    timer.schedule(new looper(), new Date());

Will the TimerTask create a new thread? if so, how does runOnUiThread will work? will it move the code to the UI thread?

I've tried to eliminate the need to call the TimerTask again (timer.schedule) and just use an infinite loop inside the run to make calculations - but that would block the UI thread and the app will not respond.

P.S - I must have the code run on the UI thread, because it has to update the UI.

So, what's going on here?

Upvotes: 1

Views: 2584

Answers (1)

AlexBcn
AlexBcn

Reputation: 2460

About your questions:

  • runOnUiThread from docs:

    Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

  • The code at TimerTask it is executed on a different thread, so you should call runOnUiThread to execute code.

You are doing it right, but why are you re-creating the timertask at the run method ? Consider using scheduleAtFixedTime , the 100 will be the period and the delay 0. The run method then will execute the task it is supposed to do.

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //do whatever
        }
    });

scheduleAtFixedTime

*Updated:

If its an update to a view it is better to use handler.postDelayed, see an example here it will be executed after a delay on the UI thread.

Upvotes: 2

Related Questions