2013-09-28 144 views
0

我已经修改了android应用“蓝牙聊天”,你可以在android sdk示例版本2.1中找到 该应用与arduino建立了蓝牙连接,当应用发送0或1时, arduino发送一条简单的消息“你已经按0或1”。 如果我使用eclipse的调试进行测试,但是当我使用我的智能手机进行测试时,显示结果不同,arduino的字符串被分割通讯蓝牙android-arduino

示例:智能手机:0 - > arduino“您按0或1” 智能手机显示屏:“y” “ou pr”

字符串的其余部分丢失或未显示在显示屏中。 你能帮我吗? logcat没有错误,只有这个错误。

这是代码:

public class BluetoothLampService { 
    // Debugging 
    private static final String TAG = "BluetoothLampService"; 
    private static final boolean D = true; 

    // Name for the SDP record when creating server socket 
    private static final String NAME = "BluetoothLamp"; 

    // Unique UUID for this application - Standard SerialPortService ID 
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 



    // Member fields 
    private final BluetoothAdapter Adapter; 
    private final Handler Handler; 
// private AcceptThread AcceptThread; 
    private ConnectThread ConnectThread; 
    private ConnectedThread ConnectedThread; 
    private int State; 

    // Constants that indicate the current connection state 
    public static final int STATE_NONE = 0;  // we're doing nothing 
    public static final int STATE_LISTEN = 1;  // now listening for incoming connections 
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection 
    public static final int STATE_CONNECTED = 3; // now connected to a remote device 

    /** 
    * Constructor. Prepares a new BluetoothChat session. 
    * @param context The UI Activity Context 
    * @param handler A Handler to messages back to the UI Activity 
    */ 
    public BluetoothLampService(Context context, Handler handler) { 
     Adapter = BluetoothAdapter.getDefaultAdapter(); 
     State = STATE_NONE; 
     Handler = handler; 
    } 

    /** 
    * Set the current state of the chat connection 
    * @param state An integer defining the current connection state 
    */ 
    private synchronized void setState(int state) { 
     State = state; 

     // Give the new state to the Handler so the UI Activity can update 
     Handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); 
    } 

    /** 
    * Return the current connection state. */ 
    public synchronized int getState() { 
     return State; 
    } 

    /** 
    * Start the chat service. Specifically start AcceptThread to begin a 
    * session in listening (server) mode. Called by the Activity onResume() */ 
    public synchronized void start() { 

     // Cancel any thread attempting to make a connection 
     if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;} 

     // Cancel any thread currently running a connection 
     if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;} 

     // Start the thread to listen on a BluetoothServerSocket 
//  if (AcceptThread == null) { 
//   AcceptThread = new AcceptThread(); 
//   AcceptThread.start(); 
    //  } 
     setState(STATE_LISTEN); 
    } 

    /** 
    * Start the ConnectThread to initiate a connection to a remote device. 
    * @param device The BluetoothDevice to connect 
    */ 
    public synchronized void connect(BluetoothDevice device) { 

     // Cancel any thread attempting to make a connection 
     if (State == STATE_CONNECTING) { 
      if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;} 
     } 

     // Cancel any thread currently running a connection 
     if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;} 

     // Start the thread to connect with the given device 
     ConnectThread = new ConnectThread(device); 
     ConnectThread.start(); 
     setState(STATE_CONNECTING); 
    } 

    /** 
    * Start the ConnectedThread to begin managing a Bluetooth connection 
    * @param socket The BluetoothSocket on which the connection was made 
    * @param device The BluetoothDevice that has been connected 
    */ 
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { 

     // Cancel the thread that completed the connection 
     if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;} 

     // Cancel any thread currently running a connection 
     if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;} 

     // Cancel the accept thread because we only want to connect to one device 
//  if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;} 

     // Start the thread to manage the connection and perform transmissions 
     ConnectedThread = new ConnectedThread(socket); 
     ConnectedThread.start(); 

     // Send the name of the connected device back to the UI Activity 
     Message msg = Handler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME); 
     Bundle bundle = new Bundle(); 
     bundle.putString(MainActivity.DEVICE_NAME, device.getName()); 
     msg.setData(bundle); 
     Handler.sendMessage(msg); 

     setState(STATE_CONNECTED); 
    } 

    /** 
    * Stop all threads 
    */ 
    public synchronized void stop() { 
     if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;} 
     if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;} 
    //  if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;} 
     setState(STATE_NONE); 
    } 

    /** 
    * Write to the ConnectedThread in an unsynchronized manner 
    * @param out The bytes to write 
    * @see ConnectedThread#write(byte[]) 
    */ 
    public void write(byte[] out) { 
     // Create temporary object 
     ConnectedThread r; 
     // Synchronize a copy of the ConnectedThread 
     synchronized (this) { 
      if (State != STATE_CONNECTED) return; 
      r = ConnectedThread; 
     } 
     // Perform the write unsynchronized 
     r.write(out); 
    } 

    /** 
    * Indicate that the connection attempt failed and notify the UI Activity. 
    */ 
    private void connectionFailed() { 
     setState(STATE_LISTEN); 

     // Send a failure message back to the Activity 
     Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST); 
     Bundle bundle = new Bundle(); 
     bundle.putString(MainActivity.TOAST, "Unable to connect device"); 
     msg.setData(bundle); 
     Handler.sendMessage(msg); 
    } 

    /** 
    * Indicate that the connection was lost and notify the UI Activity. 
    */ 
    private void connectionLost() { 
     setState(STATE_LISTEN); 

     // Send a failure message back to the Activity 
     Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST); 
     Bundle bundle = new Bundle(); 
     bundle.putString(MainActivity.TOAST, "Device connection was lost"); 
     msg.setData(bundle); 
     Handler.sendMessage(msg); 
    } 

    /** 
    * This thread runs while listening for incoming connections. It behaves 
    * like a server-side client. It runs until a connection is accepted 
    * (or until cancelled). 
    */ 
    /* 
    private class AcceptThread extends Thread { 
     // The local server socket 
     private final BluetoothServerSocket ServerSocket; 

     public AcceptThread() { 
      BluetoothServerSocket tmp = null; 

      // Create a new listening server socket 
      try { 
       tmp = Adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); 
      } catch (IOException e) { 
       } 
      ServerSocket = tmp; 
     } 

     public void run() { 
      //Looper.prepare(); 

      setName("AcceptThread"); 
      BluetoothSocket socket = null; 

      // Listen to the server socket if we're not connected 
      while (State != STATE_CONNECTED) { 
       try { 
        // This is a blocking call and will only return on a 
        // successful connection or an exception 
        socket = ServerSocket.accept(); 
       } catch (IOException e) { 
        break; 
        } 

       // If a connection was accepted 
       if (socket != null) { 
        synchronized (BluetoothLampService.this) { 
         switch (State) { 
             case STATE_LISTEN: 
             case STATE_CONNECTING: 
             // Situation normal. Start the connected thread. 
             connected(socket, socket.getRemoteDevice()); 
             break; 
             case STATE_NONE: 
             case STATE_CONNECTED: 
              // Either not ready or already connected. Terminate new socket. 
              try { 
                socket.close(); 
              } catch (IOException e) { 
               } 
          break; 
         } 
        } 
       } 
      } 
     // Looper.loop(); 
     } 

     public void cancel() { 
      try { 
       ServerSocket.close(); 
      } catch (IOException e) { 
      } 
     } 
    } 
*/ 

    /** 
    * This thread runs while attempting to make an outgoing connection 
    * with a device. It runs straight through; the connection either 
    * succeeds or fails. 
    */ 
    private class ConnectThread extends Thread { 
     private final BluetoothSocket Socket; 
     private final BluetoothDevice Device; 

     public ConnectThread(BluetoothDevice device) { 
      Device = device; 
      BluetoothSocket tmp = null; 

      // Get a BluetoothSocket for a connection with the 
      // given BluetoothDevice 
      try { 
       tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
      } catch (IOException e) { 
      } 
      Socket = tmp; 
     } 

     public void run() { 
      Looper.prepare(); 
      setName("ConnectThread"); 

      // Always cancel discovery because it will slow down a connection 
      Adapter.cancelDiscovery(); 

      // Make a connection to the BluetoothSocket 
      try { 
       // This is a blocking call and will only return on a 
       // successful connection or an exception 
       Socket.connect(); 
      } catch (IOException e) { 
       connectionFailed(); 
       // Close the socket 
        try { 
         Socket.close(); 
        } catch (IOException e2) {} 

        // Start the service over to restart listening mode 
        BluetoothLampService.this.start(); 
        return; 
       } 

       // Reset the ConnectThread because we're done 
       synchronized (BluetoothLampService.this) { 
        ConnectThread = null; 
       } 
       // Start the connected thread 


       connected(Socket, Device); 
       Looper.loop(); 
     } 

     public void cancel() { 
      try { 
       Socket.close(); 
      } catch (IOException e) { 
     } 
     } 
    } 

    /** 
    * This thread runs during a connection with a remote device. 
    * It handles all incoming and outgoing transmissions. 
    */ 
    private class ConnectedThread extends Thread { 
     private final BluetoothSocket Socket; 
     private final InputStream InStream; 
     private final OutputStream OutStream; 

     public ConnectedThread(BluetoothSocket socket) { 
      Socket = socket; 
      InputStream tmpIn = null; 
      OutputStream tmpOut = null; 

      // Get the BluetoothSocket input and output streams 
      try { 
       tmpIn = socket.getInputStream(); 
       tmpOut = socket.getOutputStream(); 
      } catch (IOException e) { 
      } 

      InStream = tmpIn; 
      OutStream = tmpOut; 
     } 

     public void run() { 
      Looper.prepare(); 
      byte[] buffer = new byte[1024]; 
      int bytes; 

      // Keep listening to the InputStream while connected 
      while (true) { 
       try { 
        // Read from the InputStream 
        // FUNZIONANTE 
        bytes = InStream.read(buffer); 
        Log.i("BYTES", Integer.toString(bytes)); 

        //String dati = new String(buffer); 
        //fine aggiunto da me 


        // Send the obtained bytes to the UI Activity 
     Handler.obtainMessage(MainActivity.MESSAGE_READ, 27, -1, buffer).sendToTarget();//buffer 
       } catch (IOException e) { 
        connectionLost(); 
        break; 
        } 
      } 
      Looper.loop(); 
     } 

     /** 
     * Write to the connected OutStream. 
     * @param buffer The bytes to write 
     */ 
     public void write(byte[] buffer) { 
      try { 
       OutStream.write(buffer); 

       // Share the sent message back to the UI Activity 
     Handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); 


      } catch (IOException e) { 
       } 
     } 

     public void cancel() { 
      try { 
       Socket.close(); 
      } catch (IOException e) { 
      } 
     } 
    } 
} 

回答

0

您是否已红粉许可,您的Android应用在你的清单文件?

使用许可权的android:NAME = “android.permission.BLUETOOTH”/

使用许可权的android:NAME = “android.permission.BLUETOOTH_ADMIN”/

然后检查串行baude率的Arduino串行连接。

0

请尝试首先从您的Android手机设置中明确配对设备。通常对码是1234