如何从 Android AsyncTask 更改活动 UI? [英] How to make activity UI changes from an Android AsyncTask?

查看:22
本文介绍了如何从 Android AsyncTask 更改活动 UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我有一个将从单独的线程(使用 AsyncTask)更新的 UI 的场景中,我可以将 AsyncTask 定义为活动的内部类,但这有两个我觉得有问题的缺点:

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. 它使源文件非常大,降低了管理代码的效率
  2. 线程类难以复用

什么是好的解决方案?使用内部类,但将它所做的一切抽象给其他类?将 Activity 的引用传递给 AsyncTask?总是把AsyncTask类定义为内部类,只接受源文件会很大吗?

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?

推荐答案

我见过的很多例子只是将 Context 传递到 AsyncTask 的构造函数中.

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.

这篇关于如何从 Android AsyncTask 更改活动 UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆