【发布时间】:2019-01-29 12:46:39
【问题描述】:
我在这个函数上遇到这个错误,我是 Kotlin 编程的新手,不知道如何解决这个问题。我能找到的唯一答案是Java,我不确定如何转换它们
我不知道如何将其设为静态或尝试将其从嵌套类中取出,如果有任何帮助,将不胜感激
这个 AsyncTask 类应该是静态的,否则可能会发生泄漏(匿名 android.os.AsyncTask) 少... (⌘F1) 静态字段会泄漏上下文。
private fun detectAndFrame(imageBitmap: Bitmap) {
val outputStream = ByteArrayOutputStream()
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
val inputStream = ByteArrayInputStream(outputStream.toByteArray())
val detectTask = object : AsyncTask<InputStream, String, Array<Face>>() {
var exceptionMessage = ""
override fun doInBackground(vararg params: InputStream): Array<Face>? {
try {
publishProgress("Detecting...")
val result = faceServiceClient.detect(
params[0],
true, // returnFaceId
false, null// returnFaceAttributes:
/* new FaceServiceClient.FaceAttributeType[] {
FaceServiceClient.FaceAttributeType.Age,
FaceServiceClient.FaceAttributeType.Gender }
*/
)// returnFaceLandmarks
if (result == null) {
publishProgress(
"Detection Finished. Nothing detected"
)
return null
}
publishProgress(
String.format(
"Detection Finished. %d face(s) detected",
result.size
)
)
return result
} catch (e: Exception) {
exceptionMessage = String.format(
"Detection failed: %s", e.message
)
return null
}
}
override fun onPreExecute() {
//TODO: show progress dialog
detectionProgressDialog.show()
}
override fun onProgressUpdate(vararg progress: String) {
//TODO: update progress
detectionProgressDialog.setMessage(progress[0])
}
override fun onPostExecute(result: Array<Face>) {
//TODO: update face frames
detectionProgressDialog.dismiss()
if (exceptionMessage != "") {
showError(exceptionMessage)
}
if (result == null) return
imageTook.setImageBitmap(
drawFaceRectanglesOnBitmap(imageBitmap, result)
)
imageBitmap.recycle()
}
}
detectTask.execute(inputStream)
}
private fun drawFaceRectanglesOnBitmap(
originalBitmap: Bitmap, faces: Array<Face>?
): Bitmap {
val bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
val paint = Paint()
paint.isAntiAlias = true
paint.style = Paint.Style.STROKE
paint.color = Color.RED
paint.strokeWidth = 10f
if (faces != null) {
for (face in faces) {
val faceRectangle = face.faceRectangle
canvas.drawRect(
faceRectangle.left.toFloat(),
faceRectangle.top.toFloat(),
(faceRectangle.left + faceRectangle.width).toFloat(),
faceRectangle.top + faceRectangle.height.toFloat(),
paint
)
}
}
return bitmap
}
private fun showError(message: String) {
AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(message)
.setPositiveButton("OK") { dialog, id -> }
.create().show()
}
【问题讨论】:
-
您好,感谢 Duplicate 的 cmets,该副本是为 Java 编写的。我不确定如何将其转换为 Kotlin
-
把 Java 转换成 Kotlin 应该很容易,甚至 Android Studio 都会自动为你做,所以这不是借口,这篇文章仍然是重复的。
标签: android asynchronous kotlin