我想通過藍牙將簡單的字符串數據(如'a')從Android設備發送到其他設備。我在android sdk中查看了示例藍牙代碼,但它對我來說太複雜了。當我按下按鈕時,我無法理解如何只發送特定數據。我怎麼解決這個問題?通過藍牙發送簡單字符串的Android示例藍牙代碼
24
A
回答
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
相關問題
- 1. 通過藍牙發送字符
- 2. 在Android中通過藍牙發送字符串(字節)
- 3. 例外通過藍牙發送文本字符串
- 4. Android藍牙發送文字
- 5. Android藍牙編程的代碼示例
- 6. 通過藍牙發送和接收字符串值android
- 7. Android - 通過藍牙發送文件
- 8. 通過藍牙發送一個字節
- 9. 通過藍牙
- 10. 通過藍牙
- 11. 通過藍牙
- 12. Android藍牙編程:通過藍牙將事件/數據從藍牙耳機發送到Android手機。
- 13. 通過Android上的藍牙發送字符?
- 14. Android藍牙,發送對象
- 15. Android藍牙文件發送
- 16. iPhone藍牙通信示例
- 17. Android示例藍牙聊天
- 18. 通過藍牙的Android MessagePassing
- 19. 通過藍牙發送對象或兩個字符串?
- 20. 需要通過藍牙發送一個字符串
- 21. 如何通過藍牙從android手機發送字符到arduino?
- 22. Android藍牙例子
- 23. Android藍牙例外
- 24. Android藍牙基本代碼
- 25. 通過藍牙通過藍牙發送消息,而無需配對linux
- 26. 通過藍牙發送多個文件
- 27. 通過藍牙發送一些信息
- 28. VB.net通過藍牙發送整數
- 29. 機器人發送和通過藍牙
- 30. 通過藍牙發送文件
你可以參考[這裏]也(https://stackoverflow.com/questions/13450406/how-to-receive-serial-data-using-android-bluetooth) –