2014-04-06 14 views
24

Ben bir android cihazdan 'a' gibi basit bir dize veri bluetooth üzerinden diğerine göndermek istiyorum. Ben android sdk örnek bluetooth kodu baktım ama benim için çok karmaşık. Bir düğmeye bastığımda sadece belirli verileri nasıl gönderebileceğimi anlayamıyorum. Bu sorunu nasıl çözebilirim?Android örnek bluetooth kodu bluetooth üzerinden basit bir dize göndermek için

+0

Ayrıca [buradan] senin relpy için (https://stackoverflow.com/questions/13450406/how-to-receive-serial-data-using-android-bluetooth) –

cevap

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

Teşekkür anlamlara gelebilir. Buna ek olarak, bu mesajı başka cihazdan nasıl alabilirim? – user3374956

+0

@ user3374956 genel olarak "InputStream" kaynağındaki verileri okumalısınız. Veriler nasıl gönderilir göndericiye bağlıdır. Kodu güncelledim. – eleven

+1

gerekli izinler nelerdir? – Prasad

İlgili konular