目前我有一个AsyncTask
,它在我的RecyclerView.Adapter
中被调用,在其中我从一个URL下载文件,并且进度在我的ViewHolder
中显示。以下是我的AsyncTask
的样子:
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
int positionnumber;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... f_url) {
int count;
String pathreference = f_url[0] + ",";
positionnumber = Integer.parseInt(f_url[0]);
isDownloading.set(positionnumber, true);
try {
URL url = new URL(f_url[1]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
if (isCancelled()) {
return null;
}
if (a.equals("one")) {
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/" + setDownloadedName + ".mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
if (isCancelled()) {
input.close();
return null;
}
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
pathreference = pathreference + Environment.getExternalStorageDirectory().toString() + "/" + setDownloadedName + ".mp4";
// closing streams
output.close();
input.close();
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathreference;
}
protected void onProgressUpdate(String... progress) {
prog = progress[0];
Log.d("Progress", progress[0]);
bars.get(positionnumber).setProgress_(Float.parseFloat(progress[0]));
float p = bars.get(positionnumber).getProgress_();
if (p % 1 == 0)
notifyItemChanged(positionnumber);
}
@Override
protected void onPostExecute(String file_url) {
String[] split = file_url.split(",");
int index1 = Integer.parseInt(split[0]);
try {
videoHolderClass.get(index1).setImage(imgres[0]);
bars.get(index1).setProgress_(0);
manager.insertVideoPath(index1 + "", split[1]);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
isDownloading.set(index1, false);
Log.d("done", "filesaved");
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
Toast.makeText(c, "Network Error..", Toast.LENGTH_SHORT).show();
prog = "";
networkFailed = "yes";
videoHolderClass.get(index1).setImage(imgres[1]);
bars.get(index1).setProgress_(0);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
isDownloading.set(index1, false);
}
}
}
RecyclerView
在一个片段中,该片段填充在Activity
- ViewPager
中。
现在,每当我关闭活动或转到新的活动并返回后,进度就不再显示了。
我已经看到人们这样做:
if(mtask.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
}
但问题是,AsyncTask
在我的 Adapter
中,因此我无法在片段中引用它。
我的问题:
请问有没有正确的方法来判断 AsyncTask
是否在运行,并在重新创建 Activity 时更新进度?