Android Bluetooth socket tutorial for non-blocking communication

后端 未结 1 1494
盖世英雄少女心
盖世英雄少女心 2020-12-30 11:03

I am looking for a bluetooth sample code on Android to do non-blocking socket communication.

I found several examples, like the BluetoothChat or BluetoothSocket.java

相关标签:
1条回答
  • 2020-12-30 11:53

    Looks like the answer is pretty much you can't

    however with a bit of threading magic, your can have your system work the way you want

       BluetoothSocketListener bsl = new BluetoothSocketListener(socket, handler, messageText);
        Thread messageListener = new Thread(bsl);
        messageListener.start();
    

    message system

     private class MessagePoster implements Runnable {
        private TextView textView;
        private String message;
    
        public MessagePoster(TextView textView, String message) {
          this.textView = textView;
          this.message = message;
        }
    
        public void run() {
          textView.setText(message);
        }     
      }
    

    socket listener

    private class BluetoothSocketListener implements Runnable {
    
      private BluetoothSocket socket;
      private TextView textView;
      private Handler handler;
    
      public BluetoothSocketListener(BluetoothSocket socket, 
                                     Handler handler, TextView textView) {
        this.socket = socket;
        this.textView = textView;
        this.handler = handler;
      }
    
    public void run() {
      int bufferSize = 1024;
      byte[] buffer = new byte[bufferSize];      
      try {
        InputStream instream = socket.getInputStream();
        int bytesRead = -1;
        String message = "";
        while (true) {
          message = "";
          bytesRead = instream.read(buffer);
          if (bytesRead != -1) {
            while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
              message = message + new String(buffer, 0, bytesRead);
              bytesRead = instream.read(buffer);
            }
            message = message + new String(buffer, 0, bytesRead - 1); 
    
            handler.post(new MessagePoster(textView, message));              
            socket.getInputStream();
          }
        }
      } catch (IOException e) {
        Log.d("BLUETOOTH_COMMS", e.getMessage());
      } 
    }
    }
    
    0 讨论(0)
提交回复
热议问题