【问题标题】:progressdialog bar get freeze进度对话框栏冻结
【发布时间】:2018-03-15 12:28:19
【问题描述】:

我正在上传文件并尝试在上传时使用进度条

首先我使用以下代码开始上传:

@Override
public void onClick(View v) {
    if(v== ivAttachment){

        //on attachment icon click
        showFileChooser();
    }
    if(v== bUpload){

        //on upload button Click
        if(selectedFilePath != null){
            dialog = new ProgressDialog(upload.this);
            dialog.setMax(100);
            dialog.setMessage("Subiendo Archivo...");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setProgress(0);
            dialog.show();

            //dialog.show(upload.this,"","Subiendo Archivo...",true);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //creating new thread to handle Http Operations
                    uploadFile(selectedFilePath);
                }
            }).start();

        }else{
            Toast.makeText(upload.this,"Escoge un archivo",Toast.LENGTH_SHORT).show();
        }

    }
}

然后uploadFile(selectedFilePath);从这里开始是我的代码的一部分:

File sourceFile = new File(selectedFilePath);
        int totalSize = (int)sourceFile.length();


        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);


        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length-1];

        if (!selectedFile.isFile()){
            dialog.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
                }
            });
            return 0;
        }else{
            try{
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);

                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);


                int totalBytesWritten = 0;
                Handler handler = new Handler(Looper.getMainLooper());

                        //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                        while (bytesRead > 0) {

                            //write the bytes read from inputstream
                            dataOutputStream.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                totalBytesWritten += bytesRead;
                            handler.post(new ProgressUpdater(totalBytesWritten, totalSize));

                        }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

然后在课堂之外我有这个:

private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;
        public ProgressUpdater(long uploaded, long total) {
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            onProgressUpdate((int)(100 * mUploaded / mTotal));
        }
    }


    public void onProgressUpdate(int percentage ) {
        // set current progress
        dialog.setProgress(percentage);
    }

到目前为止,我认为它可以正常工作,但它会冻结在某个数字上,例如 14/100,直到上传完成

【问题讨论】:

    标签: android file-upload progressdialog android-progressbar


    【解决方案1】:

    这里的进度条在两者之间冻结,因为您在 UI 线程上处理繁重的任务,而在 Android 中,您不应该在 UI 线程上处理繁重的任务。相反,您可以使用 AsyncTask 来实现此目的。

    来自Async task 文档:

    当一个异步任务执行时,该任务会经过 4 个步骤:

    1. onPreExecute()

    2. doInBackground(Params...)

    3. onProgressUpdate(Progress...)

    4. onPostExecute(Result)

    您也可以从中读取Progress Dialog

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多