我正在上传字符串和照片.它的工作正常.现在我想显示进度条,同时上传数据百分比,但百分比显示很快达到100%,并花费更多时间上传,最后进入后执行方法.
- protected class upload_images extends AsyncTask<String,Integer,String> {
- ProgressDialog progressDialog;
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- // showDialog(progress_bar_type);
- progressDialog = new ProgressDialog(Accept_Report.this);
- progressDialog.setCancelable(false);
- // dialog.setCanceledOnTouchOutside(false);
- progressDialog.setIndeterminate(false);
- // progressDialog.setMax(100);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- // progressDialog.setProgress(0);
- progressDialog.setMax(100);
- // progressDialog.setMessage("Loading ...");
- progressDialog.show();
- // ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar2);
- }
- @Override
- protected String doInBackground(String... params) {
- URL url;
- HttpURLConnection connection = null;
- String http=Util.URL+"reports/media/create";
- try {
- url = new URL(http);
- connection = (HttpURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.setRequestMethod("POST");
- /* connection.setConnectTimeout(50000);
- connection.setReadTimeout(50000);*/
- connection.setRequestProperty("Content-Type","application/json");
- connection.setRequestProperty("Content-Language","en-US");
- String encoded = Base64.encodeToString(("app" + ":" + "sFif4au7wet8gpsT0boK1oM2Yud6M1").getBytes("UTF-8"),Base64.NO_WRAP);
- connection.setRequestProperty("Authorization","Basic " + encoded);
- connection.setUseCaches(false);
- connection.setDoOutput(true);
- connection.connect();
- jsonArray = new JSONArray();
- right = send_right.toString().replaceAll("\\[","").replaceAll("\\]","");
- if((right!=null)&&(right!="")) {
- JSONObject pnObj = new JSONObject();
- pnObj.put("comments",right_cm);
- pnObj.put("section",right_sec);
- pnObj.put("pictures",right);
- jsonArray.put(pnObj);
- }
- // return totalSize;
- JSONObject jsonParam = new JSONObject();
- jsonParam.put("media",jsonArray);
- //Send request
- int count = 0;
- OutputStream wr = connection.getOutputStream();
- InputStream inputStream = null;
- byte[] payload = jsonParam.toString().getBytes("UTF-8");
- int totalSze = payload.length;
- Log.e("Total size ","" + totalSze);
- int bytesTransferred = 0;
- int chunkSize = (2*totalSze)/100;
- boolean last_loop = false;
- // publishProgress(0);
- while (bytesTransferred < totalSze) {
- Log.e("bytes transferred","" + bytesTransferred);
- int nextChunkSize = totalSze - bytesTransferred;
- Log.e("nextchunck",""+nextChunkSize);
- //int writer_size = wr.toString().getBytes("UTF-8").length;
- Log.e("chunk size","" + chunkSize);
- if (nextChunkSize > chunkSize) {
- nextChunkSize = chunkSize;
- }
- wr.write(payload,bytesTransferred,nextChunkSize);
- bytesTransferred += nextChunkSize;
- Log.e("byte",""+wr.toString().getBytes("UTF-8").length);
- Log.e("progress-transferred","" + bytesTransferred +" total "+totalSze);
- double cal = (( (double)bytesTransferred / (double) totalSze) * 100);
- double rounded = (double) Math.round(cal * 100.0) / 100.0;
- Log.e("progress",""+(int)rounded);
- publishProgress((int)rounded);
- wr.flush();
- wr.close();
- }catch(Exception e){
- Log.d("Exception",e.toString());
- }
- }*/
- Log.e("While loop exit","");
- /* wr.flush ();
- wr.close();*/
- }catch (OutOfMemoryError e)
- {
- e.printStackTrace();
- }
- //Get Response
- StringBuilder sb = new StringBuilder();
- HttpResultimage =connection.getResponseCode();
- Log.e("res",""+HttpResultimage);
- if(HttpResultimage==204)
- {
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
- String line = null;
- while ((line = br.readLine()) != null) {
- sb.append(line + "\n");
- }
- br.close();
- System.out.println("" + sb.toString());
- }else{
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- if(connection != null) {
- connection.disconnect();
- }
- }
- return null;
- }
- @Override
- protected void onProgressUpdate(Integer... values){
- super.onProgressUpdate(values);
- // Log.e("dfsf",""+values[0]);
- progressDialog.setProgress(values[0]);
- // progressDialog.setProgress(values[0]);
- }
- @Override
- protected void onPostExecute(String result) {
- if (HttpResultimage==204) {
- progressDialog.dismiss();
- }
- }
- }
解决方法
查看本教程 –
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
- private class UploadFileToServer extends AsyncTask<Void,String> {
- @Override
- protected void onPreExecute() {
- // setting progress bar to zero
- progressBar.setProgress(0);
- super.onPreExecute();
- }
- @Override
- protected void onProgressUpdate(Integer... progress) {
- // Making progress bar visible
- progressBar.setVisibility(View.VISIBLE);
- // updating progress bar value
- progressBar.setProgress(progress[0]);
- // updating percentage value
- txtPercentage.setText(String.valueOf(progress[0]) + "%");
- }
- @Override
- protected String doInBackground(Void... params) {
- return uploadFile();
- }
- @SuppressWarnings("deprecation")
- private String uploadFile() {
- String responseString = null;
- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
- try {
- AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
- new ProgressListener() {
- @Override
- public void transferred(long num) {
- publishProgress((int) ((num / (float) totalSize) * 100));
- }
- });
- File sourceFile = new File(filePath);
- // Adding file data to http body
- entity.addPart("image",new FileBody(sourceFile));
- // Extra parameters if you want to pass to server
- entity.addPart("website",new StringBody("www.androidhive.info"));
- entity.addPart("email",new StringBody("abc@gmail.com"));
- totalSize = entity.getContentLength();
- httppost.setEntity(entity);
- // Making server call
- HttpResponse response = httpclient.execute(httppost);
- HttpEntity r_entity = response.getEntity();
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode == 200) {
- // Server response
- responseString = EntityUtils.toString(r_entity);
- } else {
- responseString = "Error occurred! Http Status Code: "
- + statusCode;
- }
- } catch (ClientProtocolException e) {
- responseString = e.toString();
- } catch (IOException e) {
- responseString = e.toString();
- }
- return responseString;
- }
- @Override
- protected void onPostExecute(String result) {
- Log.e(TAG,"Response from server: " + result);
- // showing the server response in an alert dialog
- showAlert(result);
- super.onPostExecute(result);
- }
- }