【发布时间】:2018-07-30 15:35:25
【问题描述】:
我使用压缩图像库:https://github.com/zetbaitsu/Compressor。 该库必须运行 UI 线程,但压缩功能在非 Ui 线程内。所以我把这个函数移到了 asynctask 里面。
这是正确的方法吗?您还有其他想法吗?正确使用 asynctask execute() 还是应该使用 executeOnExecutor() 还是不使用 get() 函数?
public static class compressFile extends AsyncTask<Void, File, File> {
@Override
protected File doInBackground(Void... params) {
File thumbFile = null;
try {
thumbFile = new Compressor(MyApplication.getContext())
.setMaxWidth(width)
.setMaxHeight(height)
.setQuality(quality)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.compressToFile(new File(path), " " + System.currentTimeMillis());
} catch (Exception e) {
Mylog.printStackTrace(TAG + " error", e);
}
return thumbFile;
}
}
在非 UI 线程中压缩图像使用:
File compressedBigFile = new compressFile().execute().get();
【问题讨论】:
-
旁注:
MyApplication.getContext()暗示您对应用程序上下文有静态引用,这不是一个好习惯。您应该在AsyncTask构造函数中将上下文作为参数传递,并使用弱引用保持它。 -
好的,谢谢,之后我就照你说的写
标签: android multithreading android-asynctask compression