Android - Downloading File by updating Progress Bar

南楼画角 提交于 2019-12-12 10:12:18

问题


I have multiple files in dropbox account. I am successfully downloading files. But I want to show the progress bar with the percentage so when all files gets downloaded.The progress bar finishes.I am using AsyncTask for downloading files.here is my code.

public void onPreExecute(){

        mDialog = new ProgressDialog(mContext);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setMax(100);
        mDialog.show();
    }

    public void downloadFiles(String filename){
        Log.i("Item Name",filename);
        File dir = null;
        Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);


        if(isSDPresent){

        File sdCard = Environment.getExternalStorageDirectory();
         dir = new File (sdCard.getAbsolutePath() + "/AllSecure");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        }else{

            dir = mContext.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
            if(!dir.exists())
            {
                 dir.mkdirs();
            }     

        }

        File file = new File(dir, filename);
        try {
            FileOutputStream mFileOutputStream=new FileOutputStream(file);

            DropboxFileInfo mDropboxFileInxfo=mApi.getFile(PHOTO_DIR + filename, null, mFileOutputStream, null);

            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (DropboxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
    }


    protected String doInBackground(String... params) {

         SessionUtil ses = new SessionUtil(mContext);
            AndroidAuthSession session = ses.buildSession();
            mApi = new DropboxAPI<AndroidAuthSession>(session);


        Entry entries = null;

        try {
            System.out.println("mApi is " + mApi);
            entries = mApi.metadata(PHOTO_DIR, 10000, null, true, null);
        } catch (DropboxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        for (Entry e : entries.contents) {
            if (!e.isDeleted) {
                //Log.i("Is Folder",String.valueOf(e.isDir));
                downloadFiles(e.fileName());
                 mFileLen = entries.bytes;
                Log.i("Item Name",e.fileName());
            }
        }



       return null;
    }

    protected void onProgressUpdate(Integer... progress) {

    }

    @Override
    protected void onPostExecute(String result) {
        mDialog.dismiss();



    }

回答1:


You need to call publishProgress method in doInBackground . You need to pass your progress as argument for publishProgress method.

For example:

protected String doInBackground(String... params) {

         SessionUtil ses = new SessionUtil(mContext);
            AndroidAuthSession session = ses.buildSession();
            mApi = new DropboxAPI<AndroidAuthSession>(session);


        Entry entries = null;

        try {
            System.out.println("mApi is " + mApi);
            entries = mApi.metadata(PHOTO_DIR, 10000, null, true, null);
        } catch (DropboxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        int max = entries.contents.size(); // 2 variables need to calculate progress
        int current = 0;

        for (Entry e : entries.contents) {
            if (!e.isDeleted) {
                //Log.i("Is Folder",String.valueOf(e.isDir));
                downloadFiles(e.fileName());
                 mFileLen = entries.bytes;
                Log.i("Item Name",e.fileName());

                current++; //calculate your progress
                publishProgress(100 * current / max); //then pass it
            }
        }



       return null;
    }

After publishProgress is called onProgressUpdate will be invoked.

you need to handle progress update like this

protected void onProgressUpdate(Integer... progress) {
     Integer p = progress[0];
     mDialog.setProgress(p);
     mDialog.setMessage(String.format("%d%%", p)); //if you need to see progress percentage in dialog's text
}



回答2:


There is usefull abstract class in Dropbox API called ProgressListener, I used it like this

DBApi.getFile(dropPath, null, outputStream, new ProgressListener(){
                    @Override
                    public long progressInterval() {
                        return 500;
                    }
                    @Override
                    public void onProgress(long arg0, long arg1) {
                        int totalSize=(int) arg1;
                        int downloadedSize=(int) arg0;
                        //Here you can interact with progressbar
                    }
                });



回答3:


There are so many samples available for this. Please check this tutorial




回答4:


You can use a Progress Bar for this. The code may look like this:

private ProgressBar mProgressBar;
public void onPreExecute(){
    mProgressBar.setVisibility(ProgressBar.VISIBLE);
    }

    public void downloadFiles(String filename){
        Log.i("Item Name",filename);
        File dir = null;
        Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);


        if(isSDPresent){

        File sdCard = Environment.getExternalStorageDirectory();
         dir = new File (sdCard.getAbsolutePath() + "/AllSecure");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        }else{

            dir = mContext.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
            if(!dir.exists())
            {
                 dir.mkdirs();
            }     

        }

        File file = new File(dir, filename);
        try {
            FileOutputStream mFileOutputStream=new FileOutputStream(file);

            DropboxFileInfo mDropboxFileInxfo=mApi.getFile(PHOTO_DIR + filename, null, mFileOutputStream, null);

            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (DropboxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
    }


    protected String doInBackground(String... params) {

         SessionUtil ses = new SessionUtil(mContext);
            AndroidAuthSession session = ses.buildSession();
            mApi = new DropboxAPI<AndroidAuthSession>(session);


        Entry entries = null;

        try {
            System.out.println("mApi is " + mApi);
            entries = mApi.metadata(PHOTO_DIR, 10000, null, true, null);
        } catch (DropboxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        int size = entries.contents.size();
        int i = 0 ;
        for (Entry e : entries.contents) {
            if (!e.isDeleted) {
                //Log.i("Is Folder",String.valueOf(e.isDir));
                downloadFiles(e.fileName());
                 mFileLen = entries.bytes;
                Log.i("Item Name",e.fileName());
            }
            publishProgress(i * 100/size);
            i++;

        }



       return null;
    }

    protected void onProgressUpdate(Integer... progress) {
        mProgressBar.setProgress(values[0]);

    }

    @Override
    protected void onPostExecute(String result) {
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);



    }


来源:https://stackoverflow.com/questions/22295337/android-downloading-file-by-updating-progress-bar

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