Android:如果 AsyncTask 在单独的类中,如何从 AsyncTask 更新 UI? [英] Android: How to update an UI from AsyncTask if AsyncTask is in a separate class?

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

问题描述

我讨厌内部课程.

我有一个主要 Activity,它启动了一个短暂的"AsyncTask.

I've a main activity who launches a 'short-life' AsyncTask.

AsyncTask 在一个单独的文件中,不是主要活动的内部类

AsyncTask is in a separate file, is not an inner class of main activity

我需要异步任务从主 Activity 更新 textView.

I need async task updates a textView from main Activity.

我知道我可以从 onProgressUpdate 更新 TextView,如果 AsyncTask 是一个内部类

I know i can update a TextView from onProgressUpdate, if AsyncTask is a inner class

但是如何从一个外部的、独立的、异步的任务呢?

But how from an external, indipendent, async task ?

更新:这看起来像工作:

UPDATE: This looks like working :

在活动中我称之为任务

backgroundTask = new BackgroundTask(this);
backgroundTask.execute();

在我的构造函数中

public BackgroundTask(Activity myContext)
{
    debug = (TextView) myContext.findViewById(R.id.debugText);
}

其中 debug 是 AsyncTask 的私有字段.

where debug was a private field of AsyncTask.

所以 onProgressUpdate 我可以

So onProgressUpdate I can

debug.append(text);

谢谢大家的建议

推荐答案

AsyncTask 总是与 Activity 分开的类,但我怀疑你的意思是它与你的活动类文件在不同的文件中,所以你不能从活动的内部类中受益.只需将 Activity 上下文作为参数传递给您的异步任务(即传递给它的构造函数)

AsyncTask is always separate class from Activity, but I suspect you mean it is in different file than your activity class file, so you cannot benefit from being activity's inner class. Simply pass Activity context as argument to your Async Task (i.e. to its constructor)

class MyAsyncTask extends AsyncTask<URL, Integer, Long> {

    WeakReference<Activity> mWeakActivity;

    public MyAsyncTask(Activity activity) {
       mWeakActivity = new WeakReference<Activity>(activity);
    }

 ...

并在需要时使用(记住不要在 doInBackground() 期间使用),即在您通常调用时使用

and use when you need it (remember to NOT use in during doInBackground()) i.e. so when you would normally call

int id = findViewById(...)

在 AsyncTask 中调用,即

in AsyncTask you call i.e.

Activity activity = mWeakActivity.get();
if (activity != null) {
   int id = activity.findViewById(...);
}

请注意,我们的 Activity 可以在 doInBackground() 进行时消失(因此返回的引用可以变为 null),但是通过使用 WeakReference 我们不会阻止 GC 收集它(并泄漏内存),并且随着 Activity 消失,即使尝试更新它的状态通常也毫无意义(仍然,取决于您可能想要做的逻辑)诸如更改内部状态或更新数据库之类的事情,但必须跳过触摸 UI).

Note that our Activity can be gone while doInBackground() is in progress (so the reference returned can become null), but by using WeakReference we do not prevent GC from collecting it (and leaking memory) and as Activity is gone, it's usually pointless to even try to update it state (still, depending on your logic you may want to do something like changing internal state or update DB, but touching UI must be skipped).

这篇关于Android:如果 AsyncTask 在单独的类中,如何从 AsyncTask 更新 UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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