gpt4 book ai didi

Android使用HttpClient创建多个AsyncTask并按顺序返回数据

转载 作者:行者123 更新时间:2023-11-29 21:49:36 25 4
gpt4 key购买 nike

我正在创建多个 AsyncTasks 来将数据发送到我的服务器。在 SendOnlyOneFact 中,我发送了几个图像、gps 位置、字符串、声音……所有这些都转换为 Base64 字符串,然后,我的服务器每次获取数据时都会用一个 ID 回复我,所以我将它保存在字段“id_Data”中。我的问题是我需要按顺序获取服务器的回复,也就是说,我需要类似于“Asynctasks ordered”的东西,因为我需要它们执行其他操作。

我正在使用 API 8。感谢任何帮助。这是我的代码。

在主程序中:

for (int k=0; k<activities.size(); k++){
new SendOnlyOneFact().execute(definition, act, null, k);
}

类 SendOnlyOneFact:

private class SendOnlyOneFact extends AsyncTask<Object, Void, Void>{
private HttpResponse response;
private int kkk;
private HttpClient httpClient;

@Override
protected void onPreExecute(){
httpClient = new DefaultHttpClient();
}
@Override
protected void onProgressUpdate(Void... values){}
@Override
protected Void doInBackground(Object... params) {
kkk = ((Integer) params[3]);
actividades.get(kkk).saveData((android.app.Activity) params[1]);
// Serializar los datos creados
String cosa_serializada = actividades.get(kkk).getMeasure().serializeData(actividades.get(kkk), (android.app.Activity) params[1]);



HttpHost targetHost = new HttpHost(((GateDefinition) params[0]).getServer(), ((GateDefinition) params[0]).getPort(), "http");

HttpPost httpPost = new HttpPost("http://" + ((GateDefinition) params[0]).getServer() + ":" + ((GateDefinition) params[0]).getPort() + "/" + ((GateDefinition) params[0]).getWeb_service());
// Also be sure to tell the server what kind of content we are sending
httpPost.setHeader("content-type", "text/plain");
try {
StringEntity entity = new StringEntity(cosa_serializada, "UTF-8");
entity.setContentType("text/plain");
httpPost.setEntity(entity);

// execute is a blocking call, it's best to call this code in a
// thread separate from the ui's
response = httpClient.execute(targetHost, httpPost);

entity.consumeContent();
} catch (SocketException ex){
Log.e("SendOnlyOneFact", "No existe conexión con el servidor");
ex.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result){
if (response != null){
try {
this.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

BufferedReader reader = null;
String respuesta = null;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
respuesta = reader.readLine();
actividades.get(kkk).getMeasure().setId_Data(respuesta);

Log.i("onPostExecute SendOnlyOneFact", "Llegó un ID: " + respuesta);
reader.close();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException ex){
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// Entra aquí cuando ocurre una excepción
// La IP del servidor es incorrecta
// El servidor no está ejecutándose
Toast.makeText(mActivity, "Imposible conectar con el servidor.", Toast.LENGTH_LONG).show();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}

最佳答案

我认为您想要的是一种序列化执行 AsyncTasks 的方法,为此您可以删除 for 循环并在 onPostExecute 中启动下一个 asyncTask。另一种方法是放弃 AsyncTasks 并使用 ThreadPoolExecutor.newSingleThreadExecutor。

关于Android使用HttpClient创建多个AsyncTask并按顺序返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14760770/

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