【发布时间】:2017-12-21 14:35:23
【问题描述】:
目前
我正在从库中挑选一个文件并将其复制到指定的文件夹中。在复制时,我显示的是ProgressDialog,我正在使用AsyncTask 进行此操作。
我试图用百分比显示正在复制的文件的进度,但我遇到的问题是进度显示为 50% 并保持在 50% 直到文件完成复制。
这方面有很多问题,但都是与从URL下载有关。
我的问题
如何获取正在复制的文件的当前进度并将其显示为百分比?
请看我在下面的尝试:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == SELECT_VIDEO_REQUEST && resultCode == RESULT_OK)
{
if(data.getData()!=null)
{
new MyCopyTask().execute(data.getData());
}else{
Toast.makeText(getApplicationContext(), "Failed to select video" , Toast.LENGTH_LONG).show();
}
}
}
private class MyCopyTask extends AsyncTask<Uri, Integer, File> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.show();
}
@Override
protected File doInBackground(Uri... params) {
//copy file to new folder
Uri selectedImageUri = params[0];
String sourcePath = getRealPathFromURI(selectedImageUri);
File source = new File(sourcePath);
String filename = sourcePath.substring(sourcePath.lastIndexOf("/")+1);
//onProgressUpdate(50);
publishProgress(50);
File destination = new File(Environment.getExternalStorageDirectory(), "MyFolder/Videos/"+filename);
try
{
FileUtils.copyFile(source, destination);
}
catch (IOException e)
{
e.printStackTrace();
}
return destination;
}
@Override
protected void onProgressUpdate(Integer... values){
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(File result) {
if(result.exists()) {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(result)));
Toast.makeText(getApplicationContext(),"Stored at: "+"---"+result.getParent()+"----"+"with name: "+result.getName(), Toast.LENGTH_LONG).show();
progressDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(),"File could not be copied", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
}
【问题讨论】:
标签: android android-asynctask android-progressbar