How should I be using AsyncTask class coupled with a progress bar to perform the copying process of a file to another directory in the local context of the phone sdcard? I have seen a simil开发者_运维问答ar example [here][1], but I have no idea how to incorporate the differences/modify the context of the code to suit my context to make it work?
It would be something like
// 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");
}
}
Now, inside copyFiles you will have to call publishProgress() with size of data transferred, for example. Note that progress generic parameter is Long. You can use CountingInputStream wrapper from commons-io for that.
There are number of additional things top take care of, but in the nutshell that is it.
To start:
MyTask task = new MyTask();
task.execute(src,dest);
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
精彩评论