2014-04-06 113 views
24

我想通過藍牙將簡單的字符串數據(如'a')從Android設備發送到其他設備。我在android sdk中查看了示例藍牙代碼,但它對我來說太複雜了。當我按下按鈕時,我無法理解如何只發送特定數據。我怎麼解決這個問題?通過藍牙發送簡單字符串的Android示例藍牙代碼

+0

你可以參考[這裏]也(https://stackoverflow.com/questions/13450406/how-to-receive-serial-data-using-android-bluetooth) –

回答

34
private OutputStream outputStream; 
private InputStream inStream; 

private void init() throws IOException { 
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if (blueAdapter != null) { 
     if (blueAdapter.isEnabled()) { 
      Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices(); 

      if(bondedDevices.size() > 0) { 
       Object[] devices = (Object []) bondedDevices.toArray(); 
       BluetoothDevice device = (BluetoothDevice) devices[position]; 
       ParcelUuid[] uuids = device.getUuids(); 
       BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); 
       socket.connect(); 
       outputStream = socket.getOutputStream(); 
       inStream = socket.getInputStream(); 
      } 

      Log.e("error", "No appropriate paired devices."); 
     } else { 
      Log.e("error", "Bluetooth is disabled."); 
     } 
    } 
} 

public void write(String s) throws IOException { 
    outputStream.write(s.getBytes()); 
} 

public void run() { 
    final int BUFFER_SIZE = 1024; 
    byte[] buffer = new byte[BUFFER_SIZE]; 
    int bytes = 0; 
    int b = BUFFER_SIZE; 

    while (true) { 
     try { 
      bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+2

感謝您的relpy。除此之外,如何從其他設備接收此消息? – user3374956

+0

@ user3374956通常您需要從'InputStream'讀取數據。如何接收數據取決於發件人。我更新了代碼。 – eleven

+1

所需的許可是? – Prasad