我想在后台复制文件并每隔n秒更新一次进度。Android AsyncTask每秒复制并更新
现在,当新百分比大于先前百分比时,下面的代码会更新进度。这对于小文件来说是分崩离析的,因为它速度很快并且落后于UI线程。
所以我的问题是如何复制背景中的文件,但每n秒发布一次进度。另外我怎样才能计算它的复制速度?
的什么,我试图模仿是一个下载通知一个很好的例子,它显示的速度,比例,并在〜2000毫秒间隔
这是我使用复制的代码更新它们,在doInBackground()
方法
startTime = System.currentTimeMillis();
FileInputStream input = null;
FileOutputStream output = null;
totalMegaBytes = new File(source).length();
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte [] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) > 0) {
total += length;
latestPercentDone = (int) ((total/(float) totalMegaBytes) * 100);
if (percentDone != latestPercentDone) {
percentDone = latestPercentDone;
publishProgress(""+percentDone);
}
output.write(buffer, 0, length);
}
//flush remaning information
output.flush();
//close stream
output.close();
input.close();
你一定要考虑的Rx对于这种或者问题,这将是很容易做到这一点:https://github.com/davidmoten/rxjava-file –