2014-04-06 28 views
24

Chcę wysłać proste dane ciąg znaków, takie jak "a" z urządzenia z systemem Android na inny za pośrednictwem Bluetooth. Wyglądałem na przykładowy kod bluetooth w Android SDK, ale jest to dla mnie tak skomplikowane. Nie rozumiem, jak mogę przesłać tylko określone dane po naciśnięciu przycisku. Jak mogę rozwiązać ten problem?Android przykładowy kod bluetooth, aby wysłać prosty ciąg przez bluetooth

+0

Można odnieść [tutaj] także (https://stackoverflow.com/questions/13450406/how-to-receive-serial-data-using-android-bluetooth) –

Odpowiedz

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

Dziękujemy za relpy. Oprócz tego, w jaki sposób mogę odebrać tę wiadomość z innego urządzenia? – user3374956

+0

@ user3374956 ogólnie należy odczytać dane z 'InputStream'. Sposób odbierania danych zależy od nadawcy. Zaktualizowałem kod. – eleven

+1

wymagane pozwolenia? – Prasad