App does not run, receiving data from bluetooth, Android Java

Viewed 18

I have to receive data from bluetooth (bytes), and when I display it in console, it works fine, as expected. But app does not run, it just stops loading and that's all. That's a case when I use while (true), otherwise it does not work in real time.

Main attention to while loop and

static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// TextView myAwesomeTextView = (TextView)findViewById(R.id.textView);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BluetoothAdapter btadapter = BluetoothAdapter.getDefaultAdapter();

    Button button1 = (Button) findViewById(R.id.button);

    System.out.println(btadapter.getBondedDevices());
    BluetoothDevice hc06 = btadapter.getRemoteDevice("98:D3:31:B3:15:81");
    System.out.println(hc06.getName());
    BluetoothSocket btSocket = null;
    int counter = 0;
    do {
        try {
            btSocket = hc06.createRfcommSocketToServiceRecord(mUUID);
            System.out.println(btSocket);
            btSocket.connect();
            System.out.println(btSocket.isConnected());
        } catch (IOException e) {
            e.printStackTrace();
        }
        counter++;
    } while (!btSocket.isConnected() && counter < 3);


    InputStream inputStream = null;
    try {

        inputStream = btSocket.getInputStream();
        inputStream.skip(inputStream.available());
        byte[] b = new byte[6];


        while (true) {

            //inputStream.read(b);
            System.out.println(b[0]);
            inputStream.read(b);

            if (b[0] == 2) {
                button1.setBackgroundColor(Color.GREEN);
            } else {
                button1.setBackgroundColor(Color.RED);
            }

        }

    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

}

0 Answers
Related