Praveen
Praveen

Reputation: 101

Attach a runnable to UI thread without using Handler

I will come out straight that this is a assignment question .So I am not looking for a answer but a better answer .

We have a Async Task which takes in three parameters . The progress parameter(i.e 2nd parameter is) is a Runnable .

@Override
    public void onProgressUpdate(Runnable ...runnableCommands) {
        // TODO -- you fill in here with the appropriate call to
        // the runnableCommands that will cause the progress
        // update to be displayed in the UI thread.
    }

I am able to make calls to this method using publishProgress() in doInBackGround() method.

The challenge is to have this runnable attached to UI Thread. I know that onProgressUpdate() has access to UI thread and we can create a handler to add to message queue . But apparently it is excessive.

Can some guide me to a better way to do this than create a handler

Upvotes: 0

Views: 389

Answers (2)

T-D
T-D

Reputation: 373

According to the documentation

onProgressUpdate

This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running.

You can find a link here AsyncTask

Basically this method already runs on the UI thread. So you dont need any further code (via handelrs or runOnUiThread()).

In your case, you can just directly call run of that Runnable.

Upvotes: 0

telkins
telkins

Reputation: 10540

If you have a reference an Activity, an easy way is using the runOnUiThread(Runnable runnable) method. Looking at the source code, it's really easy to see why:

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

If you have a reference only to a View, you can use the post(Runnable runnable) method.

The JavaDoc for both states the Runnable will be executed on the main thread.

Upvotes: 2

Related Questions