Как передать изображения/изображение InputStream/OutputStream и отобразить в imageView
Есть приложение, которое передаёт через WiFi direct строку в виде байтов. Как мне реализовать передачу файлов? Добавил urisList - список Uri файлов, получилось вытянуть File в ByteArray. И передать на устройство.
Вопросы:
- Как произвести вывод изображения в imageView? В
Handlerесли выводить в imageView:
val readBuff = msg.obj as ByteArray
val bitmap = BitmapFactory.decodeByteArray(readBuff, 0, readBuff.size)
Glide
.with(this)
.load(bitmap)
.into(this.imageView!!)
Изображение не устанавливается, байты по логам приходят, те же, что и были отправлены, но Log.e("RESULT", readBuff.toString()) повторяются с байтами около 20-30 раз (как я понял, оправляются 20-30 раз).
2. Как передать несколько файлов?
private var buttonOnOff: Button? = null
private var buttonSend: Button? = null
private var textViewRead: TextView? = null
var connectionStatus: TextView? = null
private var writeMsg: EditText? = null
private var wifiManager: WifiManager? = null
private var mManager: WifiP2pManager? = null
private var mChannel: WifiP2pManager.Channel? = null
private var mReceiver: BroadcastReceiver? = null
private var mIntentFilter: IntentFilter? = null
private var peers: MutableList<WifiP2pDevice> = ArrayList()
private var deviceNameArray: Array<String?> = arrayOf()
private var deviceArray: Array<WifiP2pDevice?> = arrayOf()
private var serverClass: ServerClass? = null
private var clientClass: ClientClass? = null
private var sendReceive: SendReceive? = null
private var urisList = mutableListOf<Uri?>()
var handler: Handler = Handler(Looper.getMainLooper()) { msg ->
when (msg.what) {
MESSAGE_READ -> {
val readBuff = msg.obj as ByteArray
val bitmap = BitmapFactory.decodeByteArray(readBuff, 0, readBuff.size)
Glide
.with(this)
.load(bitmap)
.into(this.imageView!!)
}
}
true
}
buttonSend!!.setOnClickListener {
val path = getPath(urisList[0]!!)
val file = File(path)
if (file.exists()) {
sendReceive?.write(file.readBytes())
}
}
inner class SendReceive(private val socket: Socket?) : Thread() {
private var inputStream: InputStream? = null
private var outputStream: OutputStream? = null
override fun run() {
val buffer = ByteArray(1024)
var bytes: Int
while (socket != null) {
try {
bytes = inputStream!!.read(buffer)
if (bytes > 0) {
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}
fun write(bytes: ByteArray?) {
GlobalScope.launch {
try {
outputStream!!.write(bytes)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
init {
try {
inputStream = socket!!.getInputStream()
outputStream = socket.getOutputStream()
} catch (e: IOException) {
e.printStackTrace()
}
}
}