In my Android app, I want to use the Camera
intent, which returns an onActivityResult
I coded the start Camera in a separate function, and calling it as:
// MainActivity.kt
btnCamera.setOnClickListener {
startCamera(this)
}
And doing the same for the onActivityResult
and calling it as:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
onCameraActivityResult(this, requestCode, resultCode, data)
}
In the onCameraActivityResult
I’m calling another function that is using opencv
, and call another function named detectFace
:
fun onCameraActivityResult(context: Context, requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
...
detectFace(context, bitmap, faces_value)
}
}
The detectFace
functionusing coroutine, so it is required to be a
suspend` function as:
suspend fun detectFace(context: Context, image: Bitmap, facesValue: TextView) {
val frame = AndroidFrameConverter().convert(image)
val mat = OpenCVFrameConverter.ToMat().convert(frame)
coroutineScope {
launch {
// delay(1000)
// println("Kotlin Coroutines World!")
val numberOfFaces = FaceDetection.detectFaces(mat).toString()
(context as Activity).runOnUiThread {
facesValue.text = numberOfFaces
}
}
// println("Hello")
}
}
As detectFace
is required to be a suspend
, then the one calling it onCameraActivityResult
is required to be a suspend
too, also the one calling this, which is onActivityResult
is required to be a suspend
too.
So, I ended having:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
btnCamera.setOnClickListener {
startCamera(this)
}
}
override suspend fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
onCameraActivityResult(this, requestCode, resultCode, data)
}
}
And here I ended with this error: