返回值从AsyncTask的无get()方法 [英] Return value from AsyncTask without get() method

查看:207
本文介绍了返回值从AsyncTask的无get()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的DoInBackground AsyncTask的返回值,而是调用get()方法冻结我的用户界面。我怎样才能重新写我的code到回调方法?

I'm trying to return value from my asynctask in DoInBackground, but calling get() method freezes my UI. How can I re-write my code to a callback method? :

public class GetUrlDataTask extends AsyncTask<String, Integer, String> {
String response;
HttpUtils util;
@Override
protected String doInBackground(String... params) {
    try {
        util = new HttpUtils(params[0]);
        response = util.getContent();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return response;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
}

在我的活动我得到的结果为响应=新GetUrlDataTask()执行(简称网站)获得;

In my activity I get result as response = new GetUrlDataTask().execute("site").get;

推荐答案

[更新]现在,我建议使用注解。使用注释你可以注入的意见,使功能上,只需几个字母编译步骤asyncronous过程。看看在GitHub上butterknife库。

[UPDATE] Now i suggest to use annotations. With annotations you can inject views, make function as asyncronous process on the compilation step with just a few letters. Check out butterknife library on github.

ButterKnife

您可以创建界面,它传递给AsyncTask的(在构造函数),然后调用onPostExecute方法

You can create interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute

例如:

您接口:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

您活动:

public YourActivity implements OnTaskCompleted{
    //your Activity
}

和你的AsyncTask:

And your AsyncTask:

public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    //required methods

    protected void onPostExecute(Object o){
        //your stuff
        listener.onTaskCompleted();
    }
}

这篇关于返回值从AsyncTask的无get()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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