Android匿名asyncTask在方法中返回值

时间:2014-11-27 10:25:43

标签: java android android-asynctask

现在在我的应用程序中,我尝试从url进行http解析,但在此之前我没有携带线程...

我有这样的课程和方法:

public class TwitterOAuthHelper {
public String httpQueryToApi(String url) {
        HttpGet get = new HttpGet(url);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setUseExpectContinue(params, false);
        get.setParams(params);
        String response = null;
        try {
            SharedPreferences settings = context.getSharedPreferences("my_app", 0);
            String userKey = settings.getString("user_key", "");
            String userSecret = settings.getString("user_secret", "");
            consumer.setTokenWithSecret(userKey, userSecret);
            consumer.sign(get);
            DefaultHttpClient client = new DefaultHttpClient();
            response = client.execute(get, new BasicResponseHandler());
        } catch (Exception e) {
            displayToast("Failed to get data.");
        }
        return response;
    }

}

现在我尝试将此逻辑移动到asyncTask:

String result;
public String httpQueryToApi(String url) {
    new AsyncTask<String,Void,String>(){

        @Override
        protected String doInBackground(String... params) {
            HttpGet get = new HttpGet(String.valueOf(params));
            HttpParams param = new BasicHttpParams();
            HttpProtocolParams.setUseExpectContinue(param, false);
            get.setParams(param);
            String response = null;
            try {
                SharedPreferences settings = context.getSharedPreferences("my_app", 0);
                String userKey = settings.getString("user_key", "");
                String userSecret = settings.getString("user_secret", "");
                consumer.setTokenWithSecret(userKey, userSecret);
                consumer.sign(get);
                DefaultHttpClient client = new DefaultHttpClient();
                response = client.execute(get, new BasicResponseHandler());
            } catch (Exception e) {
                displayToast("Failed to get data.");
            }
            result = response;
            return response;
        }
    }.execute(url);
    return result;
    }

但是如何将我的响应结果值返回给方法?

这样做的最佳做法是什么?

4 个答案:

答案 0 :(得分:3)

像这样做:

@Override
protected void onPostExecute(String result) {
    //result is your returned value from doInBackground
}

如果你想要一个回调antoher方法,它应该是接口

public interface ResultInterface {
     public void resultFromHttp(String result);
}

然后你的方法

public String httpQueryToApi(String url, final ResultInterface ri){
      //as bove
    @Override
    protected void onPostExecute(String result) {
        if(ri!=null)
            ri.resultFromHttp(result);
    }

}

为您的Activity / Fragment实现ResultInterface / wahtever正在调用httpQueryToApi

答案 1 :(得分:0)

你不能,因为任务将在另一个线程中执行。

但是你可以使用回调来获得结果。 请看一下:https://stackoverflow.com/a/19520293/4299154

答案 2 :(得分:0)

最初,您的函数返回了一个字符串,然后您进一步处理。精细。 但你不能像这样使用线程。你不能从函数返回结果,因为它尚未设置(你可以,但它将返回null)。这样做的正确方法是

public void httpQueryToApi(String url) {

    new AsyncTask<String,Void,String>(){

        @Override
        protected String doInBackground(String... params) {
            HttpGet get = new HttpGet(String.valueOf(params));
            HttpParams param = new BasicHttpParams();
            HttpProtocolParams.setUseExpectContinue(param, false);
            get.setParams(param);
            String response = null;
            try {
                SharedPreferences settings = context.getSharedPreferences("my_app", 0);
                String userKey = settings.getString("user_key", "");
                String userSecret = settings.getString("user_secret", "");
                consumer.setTokenWithSecret(userKey, userSecret);
                consumer.sign(get);
                DefaultHttpClient client = new DefaultHttpClient();
                response = client.execute(get, new BasicResponseHandler());
            } catch (Exception e) {
                displayToast("Failed to get data.");
            }
            return response;
        }

        @Override
        protected void onPostExecute(String s) {

            //here s is the response string, do what ever you want
            super.onPostExecute(s);
        }
    }.execute(url);              
}

你必须将你的进一步处理逻辑转移到onPostExecute,别无他法:) 如果你想深入了解Future<>

答案 3 :(得分:0)

1)为您创建单独的类Async(非匿名)。

2)创建接口类。

public interface AsyncResponse {
    void onProcessFinish(String output);
}

3)在你的Async类中,你需要声明它(interface:AsyncResponse):

public class MyAsyncTask extends AsyncTask<String,Void,String>(){
   public AsyncResponse listener = null;    

   public MyAsyncTask(AsyncResponse l) {
        this.listener = l;
    }
   {...}
   @Override
        protected String doInBackground(String... params) {
            HttpGet get = new HttpGet(String.valueOf(params));
            HttpParams param = new BasicHttpParams();
            HttpProtocolParams.setUseExpectContinue(param, false);
            get.setParams(param);
            String response = null;
            try {
                SharedPreferences settings = context.getSharedPreferences("my_app", 0);
                String userKey = settings.getString("user_key", "");
                String userSecret = settings.getString("user_secret", "");
                consumer.setTokenWithSecret(userKey, userSecret);
                consumer.sign(get);
                DefaultHttpClient client = new DefaultHttpClient();
                response = client.execute(get, new BasicResponseHandler());
            } catch (Exception e) {
                displayToast("Failed to get data.");
            }
            result = response;
            return response;
        }


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

4)在你的类中(例如在你的Activity中调用AssyncClass)你需要实现你之前创建的AsyncResponse接口。

public class MainActivity implements AsyncResponse{



  {...}
   void onProcessFinish(String output){
     //this you will received result fired from async class of onPostExecute(result) method.
   }
}

6)现在你可以调用MainActivity:

new MyAsyncTask(this).execute("your_url");