2017-05-29 74 views
0

目前的情況數的AsyncTask的同時執行工作不正常

我有我要運行一個點擊按鈕的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的奇巧相同的代碼不會給人第一的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塊一段時間。

這是我完整的asynctask代碼。

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的currently.Can這會引起其他問題的服務器?

回答

1

聽起來像你的問題可能是你發佈的內容的長度。

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; 
} 

我不同的加我的數據,但你能適應你的解決方案。

+0

我的多重請求不是簡單的json請求 –

+0

我的觀點是這似乎是問題來自你的'httpURLConnection.addRequestProperty(「Content-length」,httpEntity.getContentLength()+「」);'我沒有看到你正在添加一個文件。我剛剛看到你正在上傳看起來不少參數。您應該檢查內容長度是否與您收到的錯誤消息大小相同。如果沒有 - 那是你的問題 – Barns

+0

感謝您的幫助,我現在已經切換到改造,它似乎正常工作 –