目前
我从图库中选择一个文件并将其复制到指定的文件夹。在复制时我正在显示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();
}
}
}
答案 0 :(得分:2)
手动复制并以百分比更新进度:
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destination);
long lenghtOfFile = source.length();
byte[] buf = new byte[512];
int len;
long total;
while ((len = in.read(buf)) != -1) {
total += len;
publishProgress((int)((total*100)/lenghtOfFile));
out.write(buf, 0, len);
}
in.close();
out.close();
答案 1 :(得分:-1)
错误的是在publishProgress(50); 你必须发布每个百分比的进度 像这样 publishProgress(ⅰ); 我++;