我有一个类要减少映像,但我当前使用的是AsyncTask,现在我想替换它,因为AsyncTask现在已被弃用。所以有人能帮我解决的问题吗
这是我的代码:
class DecreaseImageTask(
val uri: Uri? = null,
val bitmap: Bitmap? = null,
var context: Context,
var listener: (String?) -> Unit
) : AsyncTask<Void, Long, String?>() {
override fun doInBackground(vararg params: Void?): String? {
return when {
uri != null -> {
decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "")
}
bitmap != null -> {
decreaseImageSize(bitmap = bitmap)
}
}
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
listener(result)
}
}
您可以更改decreaseImageSize
以接受回调作为参数
在这种情况下,函数将不再需要返回字符串,该字符串作为参数传递给回调函数,然后用作它体内的一个参数:
fun decreaseImageSize(imagePath: String? = null, bitmap: Bitmap? = null, callback: (String) -> Unit) {
...
val result = "" // The result of the previous decreaseImageSize function
callback(result)
}
然后,不用调用AsyncTask
,而是使用新的decreaseImageSize
函数:
decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "") { result ->
// Execute the code after the image is decreased
}
decreaseImageSize(bitmap = bitmap) { result ->
// Execute the code after the image is decreased
}