0

I am trying to display the bitmap that was created from PreviewView of Camera. It can only display once to the other android if I close the outputStream but it will close the whole socket as a result. Therefore, I can't display the next image.

Here is my code for input:

wifiClient = WiFiClient(wifiP2pInfo.groupOwnerAddress, activity)
wifiClient.start()
wifiClient.write(selfCameraView.bitmap)

And here is my code for client:

class WiFiClient(
    private val inetAddress : InetAddress,
    private val activity : NetworkActivity
    ) : Thread() {

    private lateinit var inputStream : InputStream
    private lateinit var outputStream : OutputStream

    fun write (bitmap: Bitmap?) {
        val executor = Executors.newSingleThreadExecutor()
//        val handler = Handler(Looper.getMainLooper())

        executor.execute {
            try {
                if (bitmap != null) {
                    val stream = ByteArrayOutputStream()
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                    outputStream.write(stream.toByteArray())
                    outputStream.flush()
//                  outputStream.close()

                    Log.v(MainActivity.TAG, "Output Stream: $bitmap")
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    override fun run() {
        super.run()
        val socket = Socket()
//        val executor = Executors.newSingleThreadExecutor()
        val handler = Handler(Looper.getMainLooper())

        try {
            socket.connect(InetSocketAddress(inetAddress.hostAddress, 8888), 500)
            inputStream = socket.getInputStream()
            outputStream = socket.getOutputStream()
        } catch (e : IOException) {
            e.printStackTrace()
        }
        Log.v(MainActivity.TAG, "REACHED HERE")

        val buffer = ByteArray(1048576)

        try {
            var bytes = inputStream.read(buffer, 0, buffer.size)
            var current = bytes

            do {
                bytes = inputStream.read(buffer, current, (buffer.size - current))
                if (bytes >= 0) {
                    current += bytes
                }
            } while(bytes > -1)

            handler.post {
                val bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.size)
                activity.otherCameraView.setImageBitmap(bitmap)
            }

//            inputStream.close()
        } catch (e : IOException) {
            e.printStackTrace()
        } finally {
//            socket.close()
        }
    }
}

How can I fix this?

strygel
  • 1
  • 2

0 Answers0