如何使用AsyncTask类更新复制文件另一个目录的进度?
嗨,大家可以告诉我,我应该如何使用AsyncTask类加上进度条来执行文件到手机SD卡本地上下文中的另一个目录的复制过程? 我已经看到了一个类似的例子[这里] [1],但我不知道如何结合差异/修改代码的上下文以适应我的上下文使其工作?
它会是这样的
// Params are input and output files, progress in Long size of // data transferred, Result is Boolean success. public class MyTask extends AsyncTask { 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()。 请注意,progressgenerics参数为Long。 您可以使用commons-io中的CountingInputStream包装器。
还有很多额外的东西需要注意,但简而言之就是它。
开始:
MyTask task = new MyTask(); task.execute(src,dest);
尝试使用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(); }
- 在EditText上使用TextWatcher在android中实时计算总数和总和?
- 将事件添加到此日历
- 在Thread.sleep()阻塞之前调用并返回Android TextView.setText(),直到sleep()返回。 为什么?
- Android:如何将图像资源与R.drawable.imagename进行比较?
- 我怎样才能使用customadapter在listview中添加一个带有listitems的微调器?
- Android使用BroadCastReceiver阻止传入短信
- Android SU权限IOException
- Android使用dependency injection简单的自定义类
- SurfaceView显示为空,没有任何渲染