I have a listener where the user can send a POST HTTP request, but I want to let the user send as many HTTP requests as possible (He won't have to wait for the HTTP request to end), but I am not sure about whether to use Coroutines or threads. So I need to be pointed into documentation that provides a context for what I want to do.
Here is my code, where the target function to run in a thread is uploadFile:
...
findViewById<View>(R.id.screen).setOnClickListener { _: View? ->
imgCap.takePicture(object : ImageCapture.OnImageCapturedListener() {
override fun onCaptureSuccess(image: ImageProxy, rotationDegrees: Int) {
i += 1;
Log.i("Click", "Click number $i");
Toast.makeText(baseContext, "Image Captured", Toast.LENGTH_SHORT).show()
uploadFile(image)
super.onCaptureSuccess(image, rotationDegrees)
}
})
}
CameraX.bindToLifecycle(this, preview, imgCap)
}
private fun uploadFile(img: ImageProxy) {
val url = "https://5d6d-41-97-171-237.eu.ngrok.io/api/photos"
val bitmap = img.convertImageProxyToBitmap()
Log.e("bitmap", bitmap.toString())
val imgBase = convertImageToBase64(bitmap)
val bos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos)
// add parameter
val formBody = FormBody.Builder().add("photo", imgBase).build()
// creating request
var request = Request.Builder().url(url)
.post(formBody)
.build()
var client = OkHttpClient();
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
println(response.body?.string())
}
override fun onFailure(call: Call, e: IOException) {
Log.e("Exception:", e.toString())
Log.e("Error:", e.message.toString())
}
})
}