Java – How do I use the AsyncTask class to update the progress of copying a file to another directory?

How do I use the AsyncTask class to update the progress of copying a file to another directory?… here is a solution to the problem.

How do I use the AsyncTask class to update the progress of copying a file to another directory?

How should I use the AsyncTask class and progress bar to perform the process of copying files to another directory in the local context of the phone’s SD card? I saw a similar example in [here][1], but I don’t know how to merge the diff/modify the context of the code to fit my context to make it work?

Solution

It should be like this

// Params are input and output files, progress in Long size of 
// data transferred, Result is Boolean success.
public class MyTask extends AsyncTask<File,Long,Boolean> {
   ProgressDialog progress; 

  @Override
  protected void onPreExecute() {
    progress = ProgressDialog.show(ctx,"","Loading...",true);
  }

  @Override
  protected Boolean doInBackground(File... files) {
    copyFiles(files[0],files[1]);
    return true;
  }

  @Override
  protected void onPostExecute(Boolean success) {
    progress.dismiss();
    // Show dialog with result
  }

  @Override
  protected void onProgressUpdate(Long... values) {
    progress.setMessage("Transferred " + values[0] + " bytes");
  }
}

For example, now, in copyFiles, you have to call publishProgress() along with the size of the data transferred. Note that the progress common parameter is Long. To do this, you can use the CountingInputStream wrapper in commons-io.

Top has to deal with many extra things, but that’s all in short.

Begin:

  MyTask task = new MyTask();
  task.execute(src,dest);

Related Problems and Solutions