嗨,大家可以告诉我,我应该如何使用AsyncTask类和进度条来执行文件复制过程到手机SD卡本地上下文中的另一个目录?我已经看到了一个类似的例子[这里] [1]但是我不知道如何结合差异/修改代码的上下文以适应我的上下文以使其工作?
答案 0 :(得分:7)
这就像是
// 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");
}
}
现在,在copyFiles中,您必须调用带有传输数据大小的publishProgress()。请注意,进度通用参数为Long。你可以使用commons-io中的CountingInputStream包装器。
还有很多额外的东西需要注意,但简而言之就是它。
开始:
MyTask task = new MyTask();
task.execute(src,dest);
答案 1 :(得分:1)
尝试使用Async任务,如下所示:
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();
}