我選擇從庫文件並將其複製到指定的文件夾。在複製時,我顯示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();
}
}
}
你可以請更具體的,也許顯示我可以如何在我的代碼中實現這一點? – ClassA
而不是'FileUtils.copyFile(source,destination);'使用我的答案的代碼。不要忘記刪除'publishProgress(50);'。 – beeb
我得到'lenght()'的錯誤---''無法解析lenght()' – ClassA