progressdialog栏冻结 [英] progressdialog bar get freeze

查看:257
本文介绍了progressdialog栏冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



首先我用这段代码开始上传:

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

/ /附件图标点击
showFileChooser();

if(v == bUpload){

//上传按钮点击
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);
$ b $ new Thread(new Runnable(){
@Override $ b $ public void run(){
//创建新的线程来处理Http操作
uploadFile (selectedFilePath);
}
})。start();
$ b} else {
Toast.makeText(upload.this,Escoge un archivo,Toast.LENGTH_SHORT).show();



$ b $ / code $ / pre
$ b $ p然后上传文件(selectedFilePath);从这里开始是我的代码的一部分:

 文件sourceFile =新文件(selectedFilePath); 
int totalSize =(int)sourceFile.length();


HttpURLConnection连接;
DataOutputStream dataOutputStream;
String lineEnd =\r\\\
;
String twoHyphens = - ;
String boundary =*****;

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


String [] parts = selectedFilePath.split(/);
final String fileName = parts [parts.length-1]; $!
$ b if(!selectedFile.isFile()){
dialog.dismiss();

runOnUiThread(new Runnable(){
@Override
public void run(){
tvFileName.setText(Source File Does Not Exist:+ selectedFilePath );
}
});
返回0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
网址url =新网址(SERVER_URL);
connection =(HttpURLConnection)url.openConnection();
connection.setDoInput(true); //允许输入
connection.setDoOutput(true); //允许输出
connection.setUseCaches(false); //不要使用缓存的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);

//创建新的数据输出流
dataOutputStream = new DataOutputStream(connection.getOutputStream());

//将数据写入数据输出流
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes(Content-Disposition:form-data; name = \uploaded_file \; filename = \
+ selectedFilePath +\+ lineEnd);

dataOutputStream.writeBytes(lineEnd);

//返回no。 fileInputStream中存在的字节数
bytesAvailable = fileInputStream.available();
//选择缓冲区大小为可用字节的最小值或1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//将缓冲区设置为bufferSize大小的字节数组$ buffer $ b buffer = new byte [bufferSize];

//从FileInputStream中读取字节(从缓冲区的第0个索引到缓冲区大小)
bytesRead = fileInputStream.read(buffer,0,bufferSize);


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

//循环重复直到bytesRead = -1,即没有字节留下读取
while(bytesRead> 0){

//写入从输入流读取的字节
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);

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

}

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

然后出类我有这个:

  private class ProgressUpdater implements Runnable {
private long mUploaded;
私人长途mTotal;
公共ProgressUpdater(长期上传,总长){
m已上传=上传;
mTotal = total;


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



$ b public void onProgressUpdate(int percentage){
//设置当前进度
dialog.setProgress(percentage);

$ / code>

到目前为止,我认为它的工作,但它冻结在一些像14/100直到上传完成

解决方案

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



来自异步任务文档:


执行异步任务时,任务经过4个步骤: onPreExecute()



2。 doInBackground(Params ...)

< onProgressUpdate(Progress ...)



onPostExecute(结果)


您可以阅读进度对话框以及。

im uploading files and im trying to use progressbar while its uploading

frist of all i start the upload with this code:

@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();
        }

    }
}

then uploadFile(selectedFilePath); starts here is part of my code:

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);

then out of the class i have this:

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);
    }

so far i think its working but it freezes on some number like 14/100 until the upload finishes

解决方案

Here progress Bar is freezing in between because you are processing heavy task on the UI thread and in Android you should not process the heavy tasks on UI thread.Instead of this you can use the AsyncTask for this purpose.

From the Async task documentation:

When an asynchronous task is executed, the task goes through 4 steps:

1. onPreExecute()

2. doInBackground(Params...)

3. onProgressUpdate(Progress...)

4. onPostExecute(Result)

You can read Progress Dialog from this as well.

这篇关于progressdialog栏冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆