gpt4 book ai didi

android - 如何从 AsyncTasks doInBackground() 中检索数据?

转载 作者:IT老高 更新时间:2023-10-28 23:27:40 25 4
gpt4 key购买 nike

我会尽量保持这个简单。

我的控制层中有一个方法,它使用扩展 AsyncTask 的类 CallServiceTask。当调用 new CallServiceTask().execute(parameters)
如何检索 doInBackground 返回的数据?我发现的所有教程都使用直接从他们的 Activity 扩展 AsyncTask 的类。
我的问题比这要复杂一点。
我想要的只是获取 doInBackground 返回的 Object[] 并将其设置为我的 RestClient 类的私有(private)数据成员。

CallServiceTask 看起来像这样:

    private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{

protected Object[] doInBackground(Object... params)
{
HttpUriRequest req = (HttpUriRequest) params[0];
String url = (String) params[1];

return executeRequest(req, url);
}
}

我的 RestClient 类看起来像这样:

public class RestClient
{

private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;

private JSONObject jsonData;

private Object[] rtnData;

private String url;

private boolean connError;

public int getResponseCode() {
return responseCode;
}

/**
*
* @return the result of whether the login was successful by looking at the response parameter of the JSON object.
*/
public Boolean DidLoginSucceed()
{
// Will Crash on socket error
return ((JSONObject) rtnData[0]).optBoolean("response");
}

public String GetToken()
{
return jsonData.optString("token");
}

public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
rtnData = new Object[]{ new JSONObject() , Boolean.TRUE };
}

public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}

public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}

/**
* This method will execute, call the service and instantiate the JSON Object through executeRequest().
*
* @param method an enum defining which method you wish to execute.
* @throws Exception
*/
public void ExecuteCall(RequestMethod method) throws Exception
{
Object[] parameters = new Object[]{ new HttpGet() , new String("") };
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue());
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}

HttpGet request = new HttpGet(url + combinedParams);

//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
parameters[0] = request;
parameters[1] = url;

new CallServiceTask().execute(parameters);

jsonData = ((JSONObject) rtnData[0]).optJSONObject("data");
connError = (Boolean) rtnData[1];
break;

}
case POST:
{
HttpPost request = new HttpPost(url);

//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}

if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
new CallServiceTask().execute(request, url);
break;
}
}
}

private Object[] executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
client = getNewHttpClient();

HttpResponse httpResponse;

try {
httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();

if (entity != null) {

InputStream instream = entity.getContent();
String response = convertStreamToString(instream);
try {
rtnData[0] = new JSONObject(response);
rtnData[1] = false;

} catch (JSONException e1) {
rtnData[1] = true;
e1.printStackTrace();
}

// Closing the input stream will trigger connection release
instream.close();
}

} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return rtnData;
}


private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

/**
* Custom HTTP Client accepting all SSL Certified Web Services.
*
* @return n HttpClient object.
*/
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}

最佳答案

执行此操作的唯一方法是使用回调。你可以这样做:

new CallServiceTask(this).execute(request, url);

然后在你的 CallServiceTask 中添加一个本地类变量并在你的 onPostExecute 中调用该类的方法:

private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{
RestClient caller;

CallServiceTask(RestClient caller) {
this.caller = caller;
}


protected Object[] doInBackground(Object... params)
{
HttpUriRequest req = (HttpUriRequest) params[0];
String url = (String) params[1];
return executeRequest(req, url);
}

protected onPostExecute(Object result) {
caller.onBackgroundTaskCompleted(result);
}
}

然后在 RestClient 类的 onBackgroundTaskCompleted() 方法中随意使用 Object。

更优雅和可扩展的解决方案是使用接口(interface)。示例实现见 this图书馆。我刚刚开始,但它有一个你想要的例子。

关于android - 如何从 AsyncTasks doInBackground() 中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9273989/

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