Асинхронная должна быть статическая ошибка, Kotlin, Android - PullRequest
0 голосов
/ 29 января 2019

Я получаю эту ошибку в этой функции, я новичок в программировании 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()
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...