Java的AsyncTask的传递变量主线程 [英] Java AsyncTask passing variable to main thread

查看:738
本文介绍了Java的AsyncTask的传递变量主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力改变TextView的,我做在一个AsyncTask的另一个线程网络后。我试过无数的解决方案,但至今都没有奏效。

I have been trying to change textView after I'm done networking in an another thread with AsyncTask. I've tried countless solutions, but none have worked so far.

我能够实现我的目标的唯一方法是使用获得(),但它停止UI线程一段时间,这件事情我不想。

The only way I was able to achieve my goal was to use .get(), but it stops the UI thread for a while, and that's something I don't want.

我使用AsyncTask的作为外部类,并且在中间使用一个包装类,也试过。

I've also tried using the AsyncTask as an outer class, and using a wrapper class in the middle.

所以我的问题在这里,什么是得到doInBackground()和onPostExecute()使用的变量保持最简单的方法,不结冰主线程?

So my question here is, what is the easiest way to get hold of a variable used in doInBackground() and onPostExecute(), without freezing the main thread?

推荐答案

下面是一个办法做到这一点。你可以给一个回调在你的异步任务的参数,做任何你想要的和他们获得的价值从异步任务了。

Here is a way to do it. You can give a callback in parameter of your async task, do whatever you want and them get the value back from the async task.

回调接口:

public interface AsyncTaskCompleteListener<T> {
    public void onTaskComplete(T result, int number);
}

AsyncTask的:

public class LoadURL extends AsyncTask<String, Process, String> {

    private AsyncTaskCompleteListener<String> callback;

    public LoadURL(AsyncTaskCompleteListener<String> cb) {
        this.callback = cb;
     }

    protected void onPreExecute() {}

    protected String doInBackground(String... arg0) {
         // do something
        return content;
    }

    protected void onPostExecute(String content) {
        if (callback != null)
            callback.onTaskComplete(content,number);
    }
}

活动:

public class LoginActivity extends Activity implements AsyncTaskCompleteListener<String> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        LoadURL loadUrl = new LoadURL(LoginActivity.this);
        loadUrl.execute(...);
    }

    @Override
    public void onTaskComplete(String result, int number) {...}
}

在onTaskComplete,你可以轻松地修改您的TextView

in onTaskComplete, you can easily modify your TextView

这篇关于Java的AsyncTask的传递变量主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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