gpt4 book ai didi

java - Android匿名asyncTask方法中的返回值

转载 作者:行者123 更新时间:2023-12-01 22:33:55 25 4
gpt4 key购买 nike

现在在我的应用程序中,我尝试从 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;
}

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

这样做的最佳实践是什么?

最佳答案

将以下方法添加到 asynctask 主体(在 doInBackground 方法下面):

@Override
protected void onPostExecute(String result) {
// result is your returned value from doInBackground
// now we are in main ui thread
}

如果你想要回调另一个方法,它应该是接口(interface)

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/任何调用httpQueryToApi的地方实现ResultInterface,传递this 作为第二个参数(ri 接口(interface))

关于java - Android匿名asyncTask方法中的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27168275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com