Possible quick and dirty implementation:
val (ktPort, jsPort) = WebViewCompat.createWebMessageChannel(view)
WebViewCompat.postWebMessage(
view,
WebMessageCompat("init_binary_port", arrayOf(jsPort)),
"https://example.com/".toUri()
);
ktPort.setWebMessageCallback(
object : WebMessagePortCompat.WebMessageCallbackCompat() {
override fun onMessage(
port: WebMessagePortCompat,
message: WebMessageCompat?
) {
if (message?.data != null) {
CoroutineScope(Dispatchers.IO).launch {
val data = JSONObject(JSONTokener(message.data!!));
val id = data.getInt("id")
val fileName = data.getString("fileName")
val stream = activity.assets.open("www/${fileName}");
val bufferLength = stream.available();
if (bufferLength < 0) {
throw RuntimeException("Unsupported length: $bufferLength");
}
println("id: $id, file name: $fileName, size: $bufferLength")
// TODO: Replace with binary serialization
val buffer = ByteArray(bufferLength + 4)
ByteBuffer.wrap(buffer, 0, 4)
.order(ByteOrder.BIG_ENDIAN)
.putInt(id)
stream.read(buffer, 4, bufferLength)
stream.close()
withContext(Dispatchers.Main) {
port.postMessage(WebMessageCompat(buffer))
}
}
}
}
})