編輯:關於 Android 程式設計
藍牙開發可以拆成四個階段:申請權限、控制本機藍牙模組、搜尋並配對裝置、建立 Socket 傳資料。本文依序說明,並附上各階段的關鍵程式碼。
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
從 Android 12(API 31)起,上述權限被 BLUETOOTH_CONNECT 與 BLUETOOTH_SCAN 取代,且兩者都是執行期危險權限,必須動態向使用者請求;在舊版本上不在此限。
核心類別是 BluetoothAdapter:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// 開啟系統的藍牙啟用設定面板(由使用者確認)
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0x1);
// 直接開啟藍牙
adapter.enable();
// 關閉藍牙
adapter.disable();
// 開啟本機可發現性(預設 120 秒,最長可延長至 300 秒)
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
實務上建議一律用 ACTION_REQUEST_ENABLE 把決定權交給使用者,而不是靜默呼叫 enable();後者在 API 33 起需要 BLUETOOTH_CONNECT 權限,且未經告知就開啟無線電的行為也容易招致使用者反感。另外 getDefaultAdapter() 在 API 31 已 deprecated,替代做法是 BluetoothManager.getDefaultAdapter() 或 getContext().getSystemService(BluetoothManager.class).getAdapter()。
用 startDiscovery() 啟動搜尋。這是異步方法,呼叫後立刻返回,實際搜尋在系統服務中進行,約持續 12 秒;過程中可用 cancelDiscovery() 中止。
搜尋期間系統會發出三種廣播:
ACTION_DISCOVERY_START:搜尋開始。
ACTION_DISCOVERY_FINISHED:搜尋結束。
ACTION_FOUND:找到裝置,Intent 中帶有 EXTRA_DEVICE(BluetoothDevice)與 EXTRA_CLASS(BluetoothClass)。
// 接收 ACTION_FOUND 的廣播接收器
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 從 Intent 取出裝置物件
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 顯示名稱與位址,例如放進 ListView 的 adapter
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// 註冊
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
// 別忘了在 onDestroy 中 unregisterReceiver(mReceiver)
兩個裝置要在同一個 RFCOMM channel 上各持有一個 BluetoothSocket,才算建立連線。伺服器端與客戶端取得 Socket 的路徑不同:伺服器端透過 accept() 接受一筆連入,客戶端則主動開啟一條到伺服器的 channel。雙方必須使用相同的 UUID 才能配對成功。
呼叫 listenUsingRfcommWithServiceRecord(String, UUID) 取得 BluetoothServerSocket,再用 accept() 等待連線。注意 accept() 是阻塞方法,必須放在獨立執行緒中;接受連線後通常即可關閉 ServerSocket,因為 RFCOMM 同一 channel 在單一時間點只允許一個連線。
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID 是這個 App 的 UUID,客戶端必須使用同一組
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// 持續等待,直到成功或發生例外
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
// 在另一條執行緒中處理連線
manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/** 取消監聽,讓執行緒結束 */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
先取得目標裝置的 BluetoothDevice,呼叫 createRfcommSocketToServiceRecord(UUID) 取得 Socket,再呼叫 connect()。同樣是阻塞方法,需放在執行緒中。特別注意:連線前一定要先取消搜尋,否則 connect() 會變得非常慢且容易失敗。
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// 搜尋會拖慢連線,先取消
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect(); // 阻塞,直到成功或拋出例外
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
manageConnectedSocket(mmSocket);
}
/** 取消進行中的連線並關閉 Socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
透過 getInputStream() 與 getOutputStream() 取得串流,再用 read() 與 write() 讀寫。read() 會一直阻塞直到有資料;write() 通常不阻塞,但若對端未及時讀取或緩衝區已滿也會暫時停住。
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// 持續讀取,直到發生例外
while (true) {
try {
bytes = mmInStream.read(buffer);
// 交給 UI 執行緒更新畫面
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/** 由主 Activity 呼叫以送出資料 */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/** 關閉連線 */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
藍牙的每個環節幾乎都是阻塞或異步的,務必確認 accept()、connect()、read() 都跑在工作執行緒上,透過 Handler 或 runOnUiThread() 回主執行緒更新 UI。所有 Socket、ServerSocket 與串流都要有明確的關閉路徑,否則裝置配對後會出現無法再連線的僵死狀態。最後記得區分「傳統藍牙(Bluetooth Classic)」與「藍牙低功耗(BLE)」——兩者的 API 幾乎完全不同,本文的 RFCOMM 屬於前者,若要做感測器、穿戴裝置溝通,應該改用 BluetoothGatt 系列。
Android SoundRecorder 新增錄音列表選單
需求說明在 Android 錄音機範例中,原本可能只有錄音、設定與檔案類型等功能。若希望使用者能查看已存在的錄音檔,就可以新增一個錄音列表選單項。加入選單項首先在選單資源
Android Fragment 入門學習教程:從概念到實戰
Fragment 是 Android 自 Honeycomb 3.0 起才新增的概念。Fragment 雖名為「碎片」,卻和 Activity 十分相似,下
Android 移除標題欄的三種做法
1. 在 Java 程式碼中關掉 呼叫 requestWindowFeature(Window.FEATURE_NO_TITLE) 即可,但要注意必須在 setConte
Android Notification 通知實戰:震動、燈光與提示音一次搞定
通知(Notification)是 Android 中與使用者互動的重要管道,它能在不打擾當前操作的情況下,透過狀態列、震動、燈光閃爍與提示音等方式傳遞訊息。本文以一個完