2013-08-19 23 views
0

如何將publishProgress與httpPost一起使用?我看到example with urlOpenConnection,但沒有用於HttpPost。是否有可能使用publishProgress與我的代碼結構(我希望看到下載狀態)?如何在httppost中使用publishProgress?

我的AsyncTask子類

class SendData extends AsyncTask<String, Void, JSONObject> { 

     @Override 
     protected void onPreExecute() { 

      pd.setTitle("Loading..."); 

     } 

     @Override 
     protected JSONObject doInBackground(String... option) { 
      JSONObject json = null; 
      UserFunctions u = new UserFunctions(); 



      json = u.sendAdd(option); 

      return json; 
     } 

     @Override 
     protected void onPostExecute(JSONObject result) { 
      super.onPostExecute(result); 
      */ 
      do some job 
      /* 
     } 
    } 

我的JSON解析器

public JSONArray getJSONFromUrl(String url, List<NameValuePair> params, 
      int check) { 
     HttpResponse httpResponse = null; 
     InputStream is = null; 
     JSONArray jObj1 = null; 
     String json = ""; 
     HttpClient httpClient = null; 
     if (isOnline()) { 
      // pd.show(); 
      // // Making HTTP request 
      String u = url; 
      u = u + "?"; 
      try { 
       // defaultHttpClient 
       httpClient = UILApplication.getHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
       for (int i = 0; i < params.size(); i++) { 
        u = u + params.get(i).getName() + "=" 
          + params.get(i).getValue() + "&"; 
       } 
       Log.d("URL", u); 
       httpResponse = httpClient.execute(httpPost); 
       List<Cookie> cookies = ((AbstractHttpClient) httpClient) 
         .getCookieStore().getCookies(); 

       if (cookies.isEmpty()) { 
        Log.d("COOK", "response - none"); 
       } else { 
        for (int i = 0; i < cookies.size(); i++) { 
         Log.d("COOK", "response - " + cookies.get(i).toString()); 
        } 
       } 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
       Log.d("data is sent", "true"); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
       return null; 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
       return null; 
      } catch (IOException e) { 
       e.printStackTrace(); 
       return null; 

      } 
      Log.d("wait", "true"); 
      try { 

       BufferedReader reader = new BufferedReader(
         new InputStreamReader(is, "UTF-8"), 8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        // Log.d("JSON line", line); 
        sb.append(line + "\n"); 
       } 
       is.close(); 
       json = sb.toString(); 
      } catch (Exception e) { 
       Log.e("Buffer Error", "Error converting result " + e.toString()); 
       return null; 
      } 
      // try parse the string to a JSON object 
      try { 
       jObj1 = new JSONArray(json); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
       Log.e("JSON Parser", "Error parsing data " + e.toString()); 
       return null; 
      } 
      if (json.contains("error:2")) { 
       Log.e("JSON", jObj1.toString()); 

       HttpClientFactory.killSession(); 
       UILApplication.login = 2; 
       return null; 
      } 
      if (jObj1 != null) { 
       Log.d("JSON", jObj1.toString()); 
      } 
      return jObj1; 
     } 
     return null; 

    } 

用戶功能 - 爲JSON解析器NaValuePair名單。

public JSONObject sendAdd(options) { 
     // Building Parameters 
     Log.d("parsing data to sendAdd", "true"); 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("action", "add_notice")); 
       */ 
       more parameters 
       */ 
} 

請不要放棄代碼示例與url.openConection :) 編輯我intereted如何獲得價值a這將用於publishProgress(一)。我知道我可以手動設置它,例如每秒增加一次,但我希望它代表下載狀態。

+0

你只需要初始化onPreExecute一些進展觀點或TextView的,覆蓋onProgressUpdate然後調用publishProgress任何你需要更新UI –

回答

0

使用下面的代碼來顯示文件下載

1)進步創建爲0

 public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 

2)創建對話框上顯示該活動的進展開始PT

@Override 
protected Dialog onCreateDialog(int id) { 
     switch (id) { 
     case DIALOG_DOWNLOAD_PROGRESS: 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage("Downloading file.."); 
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      mProgressDialog.setCancelable(false); 
      mProgressDialog.show(); 
      return mProgressDialog; 
     default: 
      return null; 
     } 
    } 

3)下載的AsyncTask

class DownloadFileAsync extends AsyncTask<String, String, String> { 

@SuppressWarnings("deprecation") 
@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 

    showDialog(DIALOG_DOWNLOAD_PROGRESS); 
} 

@Override 
protected String doInBackground(String... aurl) { 
    int count; 
    File root = android.os.Environment.getExternalStorageDirectory();    
    // 
File dir = new File (root.getAbsolutePath()+"/downlaod");  //name of ur download folder 
    if(dir.exists()==false) { 
     dir.mkdirs(); 
      } 
File file = new File(dir, filename); //enter ur name of the file 
try { 

URL url = new URL(aurl[0]); 
URLConnection conexion = url.openConnection(); 
conexion.connect(); 

int lenghtOfFile = conexion.getContentLength(); 
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 

InputStream input = new BufferedInputStream(url.openStream()); 
OutputStream output = new FileOutputStream(file); 

byte data[] = new byte[1024]; 

long total = 0; 

    while ((count = input.read(data)) != -1) { 
     total += count; 
     publishProgress(""+(int)((total*100)/lenghtOfFile)); 
     output.write(data, 0, count); 
    } 

    output.flush(); 
    output.close(); 
    input.close(); 
} catch (Exception e) {} 
return null; 

} 
protected void onProgressUpdate(String... progress) { 
    Log.d("ANDRO_ASYNC",progress[0]); 
    mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
} 

@SuppressWarnings("deprecation") 
@Override 
protected void onPostExecute(String unused) { 
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
    Toast.makeText(this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show(); 
} 

}

4)調用異步

new DownloadFileAsync().execute(URL); //pass your url 
+0

這是不是答案。原始海報專門要求使用HttpPost的解決方案。 – colintheshots

0

請看這個例子:我用這個代碼來更新照片到服務器。

如果你想使用publishProgress請更換iNotifyProgress.notify(進度)並實現onProgressUpdate

不過,我建議你用我的方式來更新進度條。

public static class UploadPhoto extends AsyncTask<String, Void, InputStream> { 
    private static final String TAG = "UploadImage"; 
    byte[] buffer; 
    byte[] data; 
    //private long dataLength = 0; 
    private INotifyProgressBar iNotifyProgressBar; 
    private int user_id; 
    private IAddNewItemOnGridView mAddNewItemOnGridView; 
    public UploadPhoto(INotifyProgressBar iNotifyProgressBar, 
      IAddNewItemOnGridView mAddNewItemOnGridView, int user_id) { 
     this.iNotifyProgressBar = iNotifyProgressBar; 
     this.user_id = user_id; 
     this.mAddNewItemOnGridView = mAddNewItemOnGridView; 
    } 

    @Override 
    protected InputStream doInBackground(String... names) { 
     File mFile = null; 
     FileBody mBody = null; 
     File dcimDir = null; 
     try { 
      String fileName = names[0]; 
      dcimDir = Environment 
        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); 
      mFile = new File(dcimDir, Def.PHOTO_TEMP_DIR + fileName); 
      if (!mFile.isFile()) { 
       iNotifyProgressBar.notify(0, UploadStatus.FAILED); 
       return null; 
      } 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(Def.BASE_URL 
        + String.format("/%d/list", this.user_id)); 
      final int maxBufferSize = 10 * 1024; 
      mBody = new FileBody(mFile, fileName, "image/jpeg", "UTF-8"){ 
       int bytesRead, bytesAvailable, bufferSize; 
       InputStream mInputStream = super.getInputStream(); 
       int dataLength = mInputStream.available(); 
       @Override 
       public void writeTo(OutputStream out) throws IOException { 
        bytesAvailable = mInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        buffer = new byte[bufferSize]; 
        bytesRead = mInputStream.read(buffer, 0, bufferSize); 
        while (bytesRead > 0) { 
         out.write(buffer, 0, bufferSize); 
         bytesAvailable = mInputStream.available(); 
         bufferSize = Math.min(bytesAvailable, maxBufferSize); 
         bytesRead = mInputStream.read(buffer, 0, bufferSize); 
         int progress = (int) (100 - ((bytesAvailable * 1.0)/dataLength) * 100); 
         Log.d(TAG, "Result: " + progress + "%"); 
         if (progress == 100) { 
          iNotifyProgressBar.notify(progress, UploadStatus.SUCCESS); 
         } else { 
          iNotifyProgressBar.notify(progress, UploadStatus.UPLOADING); 
         } 
        } 
       } 
       @Override 
       protected void finalize() throws Throwable { 
        super.finalize(); 
        if (mInputStream != null) { 
         mInputStream.close(); 
        } 
       } 
      }; 

      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);    
      reqEntity.addPart("photo", mBody); 
      postRequest.setEntity(reqEntity); 
      HttpResponse response = httpClient.execute(postRequest); 
      InputStream mInputStream = response.getEntity().getContent(); 
      return mInputStream == null ? null : mInputStream; 
     } catch (IOException e) { 
      Log.e(TAG, "Error causes during upload image: " + e.getMessage()); 
      e.printStackTrace(); 
      iNotifyProgressBar.notify(0, UploadStatus.FAILED); 
     } finally { 
      Log.v(TAG, "Close file"); 
      if (mFile != null) { 
       mFile = null; 
      } 
      if (mBody != null) { 
       mBody = null; 
      } 
      if (dcimDir != null) { 
       dcimDir = null; 
      } 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(InputStream result) { 
     if (result == null) { 
      iNotifyProgressBar.notify(0, UploadStatus.FAILED); 
     } else { 
      PhotoInfo mPhotoInfo = ApiUtils.convertStreamToPhotoInfo(result); 
      if (mAddNewItemOnGridView != null && mPhotoInfo != null) { 
       mAddNewItemOnGridView.notifyAdded(mPhotoInfo); 
       Log.d(TAG, "Upload completed!!"); 
      } else { 
       Log.d(TAG, "Upload is failed!!"); 
       iNotifyProgressBar.notify(0, UploadStatus.FAILED); 
      } 
     } 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 
} 
相關問題