Android設備可以通過藍牙和其他設備進行通信,包括其他Android設備和外部設備,如藍牙耳機、印表機和感測器等。在本指南中,我們將詳細介紹如何使用Android藍牙API建立和管理藍牙連接。
一、檢查設備是否支持藍牙
首先,我們需要檢查當前設備是否支持藍牙功能。
private boolean isBluetoothSupported() { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter != null; }
使用上述代碼可以檢查設備是否支持藍牙功能。如果返回true,則設備支持藍牙功能。
二、開啟藍牙
在使用藍牙功能之前,需要確保藍牙已經開啟。
private boolean isBluetoothEnabled() { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter != null && bluetoothAdapter.isEnabled(); } private void enableBluetooth(Activity activity) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { Toast.makeText(this, "藍牙已打開", Toast.LENGTH_SHORT).show(); } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(this, "無法打開藍牙", Toast.LENGTH_SHORT).show(); } } }
使用上述代碼可以檢查藍牙是否已開啟。如果返回true,則藍牙已經開啟。如果返回false,則需要啟動啟用藍牙對話框以請求開啟藍牙。
三、搜索設備
在與其他設備進行通信之前,需要搜索周圍的設備。在搜索設備之前,需要確保藍牙已經開啟。
private void startDiscovery() { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isDiscovering()) { bluetoothAdapter.cancelDiscovery(); } bluetoothAdapter.startDiscovery(); Toast.makeText(this, "搜索設備中...", Toast.LENGTH_SHORT).show(); } private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(TAG, "發現設備:" + device.getName() + " - " + device.getAddress()); } } }; @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(discoveryReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(discoveryReceiver); }
使用上述代碼可以開始搜索設備。當找到設備時,會收到廣播,並且在日誌中列印設備名稱和地址。如果找不到設備,可以嘗試重新啟動搜索或檢查設備是否打開藍牙。
四、連接設備
當找到要連接的設備時,需要建立連接。建立連接前,需要確保藍牙已經開啟。
private void connect(String address) { BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); BluetoothSocket socket = null; try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); Log.d(TAG, "連接成功:" + device.getName()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
使用上述代碼可以連接指定地址的設備。如果連接成功,則會在日誌中列印設備名稱。如果連接失敗,則會拋出IOException。
五、數據傳輸
連接建立後,可以開始在設備之間傳輸數據。以下代碼演示如何發送和接收文本數據。
private void send(String message) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { return; } BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); BluetoothSocket socket = null; OutputStream outputStream = null; try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); outputStream = socket.getOutputStream(); outputStream.write(message.getBytes()); Log.d(TAG, "消息發送成功:" + message); } catch (IOException e) { e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } private final BroadcastReceiver receiveReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { Log.d(TAG, "連接成功"); } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { Log.d(TAG, "連接斷開"); } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { Log.d(TAG, "斷開請求"); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); } } }; @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); filter.addAction(BluetoothDevice.ACTION_FOUND); registerReceiver(receiveReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(receiveReceiver); }
使用上述代碼可以在設備之間傳輸文本數據。發送消息時,使用OutputStream將文本字元串轉換為位元組,並通過BluetoothSocket發送。在接收消息時,使用BroadcastReceiver監聽連接的狀態,並根據狀態更新UI或執行其他操作。
六、總結
本指南中介紹了如何使用Android藍牙API建立和管理藍牙連接。需要注意的是,在使用藍牙功能之前,需要確保藍牙已經開啟,並且在連接設備之前,需要確保已經搜索到要連接的設備。為了傳輸數據,可以使用OutputStream將文本轉換為位元組並發送。在接收數據時,可以使用BroadcastReceiver監聽連接狀態並執行操作。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/186240.html