【发布时间】:2021-08-18 02:45:59
【问题描述】:
我有一个扩展 AsyncTask 的类。调用时,此任务会将视频下载到内部存储,并依次更新进度指示器。任务完成后,它会将下载按钮更改为已下载按钮(我使用的是abdularis AndroidButtonProgress)。
该过程运行良好,但是我有一个下载按钮字段,它被突出显示为内存泄漏:
public class DownloadHandler extends AsyncTask<Object, Integer, String> {
private DownloadButtonProgress downloadButton; // This field leaks a context object
private WeakReference<Context> context;
Episode episode;
int totalSize;
public DownloadHandler(Context context) {
this.context = new WeakReference<> (context);
}
@Override
protected String doInBackground(Object... params) {
episode = (Episode) params[0];
Context context = (Context) params[1];
downloadButton = (DownloadButtonProgress) params[2];
String urlString = "https://path.to.video.mp4";
try {
URL url = new URL(urlString);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
totalSize = ucon.getContentLength();
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
String fileName = episode.getFilename() + ".mp4";
File file = new File(String.valueOf(context.getFilesDir()) + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
long total = 0;
while ((len = inStream.read(buff)) != -1) {
total += len;
if (totalSize > 0) {
publishProgress((int) (total * 100 / totalSize));
}
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
return "Downloaded";
} catch (Exception e) {
e.printStackTrace();
return "Not downloaded";
}
}
@Override
protected void onProgressUpdate(Integer... progress) {
int downloadedPercentage = progress[0];
downloadButton.setCurrentProgress(downloadedPercentage);
}
@Override
protected void onPostExecute(String result) {
if (!result.equals("Downloaded")) {
Log.d(TAG, "onPostExecute: ERROR");
} else {
downloadButton.setFinish();
// Save to Room (this is why I pass context as a weak reference)
AppDatabase db = AppDatabase.getDbInstance(context.get().getApplicationContext());
// ....
}
}
}
当我从片段中调用 DownloadHandler 时,我会这样做:
DownloadHandler downloadTask = new DownloadHandler(getActivity());
downloadTask.execute(episode, getActivity(), downloadButton);
我在执行方法中传递了下载按钮,但我需要它可用于 DownloadHandler 类中的其他方法(onProgressUpdate()、onPostExecute()),所以我将它设为一个字段。
我尝试在构造函数中将它作为弱引用传递给上下文,但我收到一个错误,提示我无法将 downloadButton 强制转换为 WeakReference。
我怎样才能使下载处理程序中的所有方法都可以使用下载按钮,但避免内存泄漏?
【问题讨论】:
标签: android memory-leaks android-asynctask