gpt4 book ai didi

java - 同时执行多个Asynctask无法正常工作

转载 作者:行者123 更新时间:2023-12-02 13:02:07 25 4
gpt4 key购买 nike

当前情况

我有一个要求,我必须在单击按钮时运行 asynctask 并将一些数据发送到服务器,并且不向用户显示任何进度。现在,如果用户再次按下按钮,将执行 asynctask 的新实例,而无需等待先前版本完成。我可以使用此类来实现这一点。

    public class AsyncTaskTools {
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
execute(task, (P[]) null);
}

@SuppressLint("NewApi")
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
}

问题

现在,当我在 Android Kitkat 中运行相同的代码时,它在第一个 asynctask 之后不会给出成功响应,并且只有当我单击按钮之间的间隔很短时才会出现成功响应。如果我等待 5-10 秒再单击按钮,那么我的代码工作得很好,但是当我快速单击按钮大约 5 次时,我的代码将无法工作。

我能够发现的与此相关的唯一问题如下

    exceeded content-length limit of 12900 bytes
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

此异常在 catch block 中的某个时间被捕获。

这是我完整的异步任务代码。

class SendCallDispositionAsyncTask extends AsyncTask<Void, Void, Void> {


public SendCallDispositionAsyncTask() {
// TODO Auto-generated constructor stub
//this.activity = profile_Info;
}

protected void onPreExecute() {
super.onPreExecute();
// utils.showProgressDialog(ActivityCallScreen.this, "Loading. Please wait..");
}

@SuppressWarnings("deprecation")
@Override
protected Void doInBackground(Void... params) {
String responseArray = null;
Log.d("asyncresponse", "do in background");
CallDurationReceiver.start_time=0;
try {
byte[] data;

try {
Log.d("callduration","Duration: "+prefManager.getDouble(PrefrenceConstants.CALL_DURATION));
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("userid", new StringBody(String.valueOf(prefManager.getInt(PrefrenceConstants.USER_ID))));
entity.addPart("dialerno", new StringBody(mobile));
entity.addPart("dipositionid", new StringBody(dispositionId));
entity.addPart("dipositiongroup", new StringBody(dipositiongroup));
entity.addPart("callduration", new StringBody(prefManager.getDouble(PrefrenceConstants.CALL_DURATION)+""));
entity.addPart("callename", new StringBody(name));
entity.addPart("calleage", new StringBody(age));
entity.addPart("callecontact", new StringBody(contact));
entity.addPart("isnote", new StringBody(checked));
entity.addPart("cbdate", new StringBody(date));
entity.addPart("aliment", new StringBody(aliment));
entity.addPart("callelocation", new StringBody(location));
entity.addPart("remarks", new StringBody(selectedRemarks));
entity.addPart("file", new FileBody(file));
entity.addPart("contactid", new StringBody(String.valueOf(contact_id)));

HttpEntity httpEntity = entity.build();
URL url = new URL(sendDispositionUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(60000);
httpURLConnection.setConnectTimeout(60000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", prefManager.getString(PrefrenceConstants.API_KEY));

httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
// httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

httpURLConnection.addRequestProperty("Content-length", httpEntity.getContentLength() + "");
httpURLConnection.addRequestProperty(httpEntity.getContentType().getName(), httpEntity.getContentType().getValue());

OutputStream os = httpURLConnection.getOutputStream();
httpEntity.writeTo(httpURLConnection.getOutputStream());
os.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
response = BufferReaderMaker.readContentFromIS(httpURLConnection.getInputStream());
Log.v("log_tag", "image upload status ::: " + response);
} else if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_CREATED) {
response = BufferReaderMaker.readContentFromIS(httpURLConnection.getInputStream());
Log.d("responce", response);


}
// {"error":true,"message":"Required field(s) userid, dialerno, dipositionid, dipositiongroup, callduration, contactid is missing or empty"}

} catch (final UnknownHostException e) {
// TODO: handle exception
Log.d("host", e.getMessage());

}
} catch (final ConnectTimeoutException e) {
// TODO: handle exception
Log.d("timeout", e.getMessage());


} catch (Exception e) {
e.printStackTrace();
Log.d("exec", e.getMessage());

}
return null;

// return "Success";

}

protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("asyncresponse", response);
// utils.hideProgressDialog();

}
}

我检查了有关此问题的多个链接,但没有一个对我有用。

有人可以告诉我这是我的代码中的问题还是服务器端的问题。

编辑

此外,我正在向服务器上传一个文件,当前大小约为 50 kb。这会导致任何问题吗?

最佳答案

听起来您的问题可能是您发布的内容的长度。

httpURLConnection.addRequestProperty("Content-length", httpEntity.getContentLength() + "");

您需要获取以字节为单位的长度。您应该检查 httpEntity.getContentLength() 返回什么值。它应该是您上传的字节数 - 包括文件的大小。

您可能对可以上传的数据量有一些限制 - 但我怀疑这就是问题所在,因为错误消息中的字节数并不多。

我使用此代码没有任何问题:

public String makeHttpRequestJsonString(String path, int requestType, Map<String, String> params){
String json = "";
InputStream responseStream = null;

try {
startTime = System.currentTimeMillis();

StringBuilder postData = new StringBuilder();
for(Map.Entry<String, String> param : params.entrySet()){
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}

byte[] postDataBytes = postData.toString().getBytes("UTF-8");

URL url = makeURL(path, requestType);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

DataOutputStream request = new DataOutputStream(conn.getOutputStream());
request.write(postDataBytes);
request.flush();
//Some people have reported issues when closing the the request before reading the
request.close();

//Check the response code of the server -
Integer replyCode = conn.getResponseCode();
//System.out.println("Reply Code: " + replyCode.toString());

responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));

String line = "";
StringBuilder stringBuilder = new StringBuilder();

while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

json = stringBuilder.toString();

}
catch (UnsupportedEncodingException e) {
} catch (IOException e) {
Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
}
return json;
}

我以不同的方式添加数据,但您可以调整您的解决方案。

关于java - 同时执行多个Asynctask无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247190/

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