Check what kind of content represent received bytes

75 views Asked by At

My Bluetooth app is able to send images too, but I can't check the type of content, if received bytes are from image, the bytes must apply to ImageView, and if received bytes are from text, the bytes must be shown on a Toast.makeText().show()

private class StreamThread extends Thread {

    public StreamThread() {

    }

    public void run() {
        byte[] buffer = new byte[1000000];
        int bytes;
        while (true) {
            try {
                bytes = bluetoothIn.read(buffer);
                //Received bytes can represent text or image
                //if (hereSomeTypeDetector=="image/*") {
                //    update the UI and show the image
                //} else if (hereSomeTypeDetector=="text/plain") {
                //    show a toast
                //}
            } catch (IOException e) {
                Log.e(TAG, "Unable to receive bytes");
                break;
            }
        }
    }

    public void write(byte[] data) {
        try {
            bluetoothOut.write(data);
        } catch (IOException e) {
            Log.e(TAG, "Unable to send bytes");
        }
    }
}

My problem is, I need to detect content type of received bytes, some code for use it instead of hereSomeTypeDetector?
NOTE:
hereSomeTypeDetector is only an example.

1

There are 1 answers

0
eduyayo On

Two ways (of the infinity of ways)

One: first byte to be the type. Kind of a header for whatever you send.

Two: serialize an object with a type field. Even, maybe, a hierarchy or... Better... Write String when you want to send texts or so