2017-05-29 14 views
0

現在のシナリオ同時実行が正常に動作していない

私は、ボタンのクリックでasynctaskを実行し、サーバーにいくつかのデータを送信する必要がありますとの任意の進捗状況が表示されません要件を持っていますユーザー。ユーザーがこのボタンをもう一度押すと、asynctaskの新しいインスタンスが実行され、前のバージョンが終了するのを待たずに実行されます。これは私がこのクラスを使って達成することができます。私はAndroidのキットカットで同じコードを実行するときに問題

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

は、今では最初asynctask後、私はそれらの間の短い間隔でボタンをクリックしすぎた場合にのみ、その成功応答を与えるものではありません。 5秒から10秒待ってからボタンをもう一度クリックするとコードは正常に動作しますが、ボタンを5回ほど速くクリックするとコードが機能しなくなります。私はこれに関連したキャッチすることができました

唯一の問題は、この例外がcatchブロックでいくつかの時間をキャッチされ、次の

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

です。

これは私の完全な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(); 

     } 
    } 

この問題に関するいくつかのリンクを確認しましたが、いずれも私のために働いていません。

これは私のコードやサーバー側の問題で何か問題があるかどうか誰に教えてもらえますか?

EDIT

はまた、私はこの原因currently.Canについて50キロバイトの任意の問題であるサーバーにファイルをアップロードするのですか?

答えて

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

私は現在、改造に切り替えてくれてありがとう助けてくれて、それは正常に動作しているようです。 –

関連する問題