2014-04-06 18 views
24

Tôi muốn gửi một dữ liệu chuỗi đơn giản như 'a' từ thiết bị Android sang thiết bị khác qua bluetooth. Tôi nhìn mẫu mã bluetooth trong sdk android nhưng nó rất phức tạp đối với tôi. Tôi không thể hiểu làm thế nào tôi có thể gửi dữ liệu cụ thể chỉ khi tôi nhấn một nút. Làm thế nào tôi có thể giải quyết vấn đề này?Mã mẫu bluetooth Android để gửi một chuỗi đơn giản qua bluetooth

+0

Bạn có thể tham khảo [ở đây] cũng (https://stackoverflow.com/questions/13450406/how-to-receive-serial-data-using-android-bluetooth) –

Trả lời

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

Cám ơn relpy của bạn. Thêm vào đó, làm thế nào tôi có thể nhận được tin nhắn này từ thiết bị khác? – user3374956

+0

@ user3374956 nói chung bạn cần phải đọc dữ liệu từ 'InputStream'. Cách nhận dữ liệu tùy thuộc vào người gửi. Tôi đã cập nhật mã. Yêu cầu phải có – eleven

+1

giấy phép? – Prasad

Các vấn đề liên quan