How to make activity UI changes from an Android As

2019-02-21 15:58发布

In a scenario where I have a UI that will be updated from a separate thread (using AsyncTask), I can define the AsyncTask as an inner class of the activity, but this has two downsides I find problematic:

  1. It makes the source files very large, reducing efficiency in managing the code
  2. It makes it hard to reuse the thread class

What's a good solution? Use an inner class, but abstract everything it does to other classes? Pass a reference to the Activity to the AsyncTask? Always define the AsyncTask class as an inner class and just accept source files will be large?

3条回答
该账号已被封号
2楼-- · 2019-02-21 16:25

Quite a few examples I have seen just pass a Context into the constructor of the AsyncTask.

public class BackgroundStuff extends AsyncTask<Void, Void, Void> {
    ...
    Context mContext;
    ...
    BackgroundStuff(Context context){
        super();
        this.mContext = context;
    }
    ...
}

I would be interested to hear if anyone else uses any other approaches.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-21 16:26

First and foremost: when using an AsyncTask you must not do UI activity within doInBackground().

What you can do is - if you want to e.g. update status for a long running background job, is to publishProgress(values) from doInBackground(). The runtime will then for those values call your onProgressUpdate(values) callback, which runs in the UI thread and from where you can update the UI.

Have a look at e.g. https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/TweetListActivity.java#L336 to see an example.

The AsyncTask can be implemented in an own class file.

查看更多
Emotional °昔
4楼-- · 2019-02-21 16:34

I have a somewhat odd P.O.V with AsyncTasks because I generally prefer using normal Threads, but essentially the way I perform a background task and update a UI is create a Handler at the end of the onCreate() method, I'll then override the handleMessage(Message msg) method.

Then in my Thread, I'll pass the Handler in as a parameter, then when I wish to make an update I'll send a message from the thread to the Handler, now what this does is communicate from the new background thread onto the UI thread to process work on the UI.

Now I imagine AsyncTasks perform a similar task but removes the need to implement override the Handlers' handleMessage method.

It'd be interesting learning more about any advantages / disadvantages between these two approaches.

查看更多
登录 后发表回答