如何解决警告:此 AsyncTask 类应该是静态的,否则可能会发生泄漏



我有以下代码:

private class ImageCompressTask extends AsyncTask<Uri, Integer, byte[]> {
@Override
protected byte[] doInBackground(Uri... uris) {
Bitmap bitmap = ImagePicker.getBitmap(getContentResolver(),uris[0]);
if (bitmap == null) {
return null;
}
Log.d(this.getClass().getName(), "doInBackground: MBs before compression: " + (double) bitmap.getByteCount() / 1e6);
byte[] bytes = getBytesFromBitmap(bitmap, 80);
Log.d(this.getClass().getName(), "doInBackground: MBs after compression: " + (double) bytes.length / 1e6);
return bytes;
}
@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
uploadData(bytes);
}
private byte[] getBytesFromBitmap(Bitmap bitmap, int quality) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
return stream.toByteArray();
}
}

它基本上将图像上传到存储,并将新文档上传到数据库(Firebase(。我收到警告:

This `AsyncTask` class should be static or leaks might occur.

试图查看以前的线程,但没有找到解决方案。如果我使类静态,那么我就不能调用getContentResolver()uploadData(bytes)。如何解决?

你显然在处理内部类。它保留对托管类的引用,在您的情况下,它是生命周期感知的东西,如活动或片段。您需要做的是:

  1. 首先不要使用AsyncTask(开玩笑,但要持保留态度(
  2. 如前所述,使您的 ImageCompressTask 静态
  3. 是否可以选择不将内容解析器作为参数传递,而是提供具有ImagePicker.getBitmap(getContentResolver(),uris[0])结果的异步任务?
  4. 您是否网络,压缩内容也在doInBackground内部,仅将onPostExecute用于任何相关结果的后处理。

最新更新