How to set Progress Bar and Progress Notification Bar for an Image Upload?

余生长醉 提交于 2019-12-11 11:44:00

问题


In my app,I am uploading a picture to a web Server ,So I want to display a Progress bar and Notification Progress Bar on notification drawer ,I have tried some methods,But the progress dialogue and Notification Bar shows different upload Percentage,I don't know, how to fix this issue.Any help is appreciated.Can anyone Help??

Method for Progress Bar. In this method I am calling the method to invoke Progress bar on Notification drawer.,and I am executing my AsyncTask task here.

ProgressDialogueBox

  public void progressDialogBox(View view){
    progress=new ProgressDialog(this);
    progress.setMessage("Uploading Image");
    progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progress.setIndeterminate(false);
    progress.setCancelable(false);
    progress.setCanceledOnTouchOutside(true);
    progress.setProgress(0);
    progress.show();
    final int totalProgressTime = 100;
    final Thread t = new Thread() {
        @Override
        public void run() {
            int jumpTime = 0;
            while(jumpTime < totalProgressTime) {
                try {

                    ProgressBarNotification();
                    new ImageUploadTask().execute();
                    sleep(2000);
                    jumpTime += 5;

                    progress.setProgress(jumpTime);
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };
    t.start();
}

Method for Progress Notification

 public void ProgressBarNotification(){
    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mBuilder = new NotificationCompat.Builder(ImageUploadActivity.this);
    mBuilder.setContentTitle("Upload")
            .setContentText("Upload in progress")
            .setSmallIcon(R.drawable.ic_launcher);

   // mBuilder.setAutoCancel(true);
    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(ImageUploadActivity.this, 0,   myIntent, Intent.FILL_IN_ACTION);
    mBuilder.setContentIntent(pendingIntent);

}

Image Upload Activity-Image uploading is done here

class ImageUploadTask extends AsyncTask<Void,Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // Displays the progress bar for the first time.
        mBuilder.setProgress(100, 0, false);
        mNotifyManager.notify(id, mBuilder.build());
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // Update progress
        mBuilder.setProgress(100, values[0], false);
        mNotifyManager.notify(id, mBuilder.build());
        super.onProgressUpdate(values);
    }

    @Override
    protected String doInBackground(Void... unsued) {
      int i;

    for (i = 0; i <= 100; i += 5) {
            // Sets the progress indicator completion percentage
        publishProgress(Math.min(i, 100));


            try {



                Thread.sleep(2 * 1000);

                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                  HttpPost httpPost = new HttpPost("http://11.10.10.14/test/upload.php");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();


                entity.addPart("uploaded_file", new ByteArrayBody(data,
                        "myImage.jpg"));

                // String newFilename= filename.concat("file");
                // newFilename=filename+newFilename;

               /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                        filename));*/
                Log.e(TAG, "Method invoked");
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                StringBuilder builder = new StringBuilder();
                String aux = "";

                while ((aux = reader.readLine()) != null) {
                    builder.append(aux);
                    if (isCancelled()) break;
                }

                String sResponse = builder.toString();

                return sResponse;


            } catch (Exception e) {
             /*   if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;*/
            }}

       // }
        return null;
    }
    @Override
    protected void onPostExecute(String sResponse) {

     if (sResponse != null) {

         Toast.makeText(getApplicationContext(),
                 "Photo uploaded successfully",
                 Toast.LENGTH_SHORT).show();

     }
       // super.onPostExecute(result);
        mBuilder.setContentText("Upload complete");
        // Removes the progress bar
    //  mBuilder.setProgress(0, 0, false);
        //mNotifyManager.notify(1, mBuilder.build());
        mNotifyManager.cancel( id);
    }
}}

Upload button

 upload = (Button) findViewById(R.id.upload);
    upload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (bitmap == null) {
                Toast.makeText(getApplicationContext(),
                        "Please select image", Toast.LENGTH_SHORT).show();
            } else {
                progressDialogBox(v);//ProgressBar on the Activity

            }
        }
    });
}

来源:https://stackoverflow.com/questions/31115961/how-to-set-progress-bar-and-progress-notification-bar-for-an-image-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!