如何在httppost中使用publishProgress?

时间:2013-08-19 09:36:01

标签: android progressdialog

如何在httpPost中使用publishProgress?我看到了example with urlOpenConnection,但没有看到HttpPost。是否可以将publishProgress与我的代码stracture一起使用(我希望看到下载状态)?

我的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给代码示例:) 编辑我的数据库如何获得将用于publishProgress(a)的值a。我知道我可以手动设置它,例如每秒增加,但我希望它代表下载状态。

2 个答案:

答案 0 :(得分:1)

使用以下代码显示文件下载进度

1)为进度为0

创建一个开始pt
      public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 

2)创建要在活动上显示的对话框

 @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

答案 1 :(得分: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();
    }
}