Android 開啟藍芽流程

慢慢的燃燒發表於2017-03-29

以下是基於Android 4.2程式碼,對Bluetooth BR/EDR Enable process的分析。BluetoothAdapter類代表的是local device Bluetooth adapter,而BluetoothDevice類代表的是remote Bluetooth device。在Android 4.3中引入了一個新的類BluetoothManager,它是一個high level manager,被用於”to obtain an instance of an BluetoothAdapter and conduct overall Bluetooth Management“。

    Bluetooth Enable process比較複雜,層次比較多,最好的分析方法是:對照logcat輸出的Bluetooth相關log來閱讀程式碼。首先從總體上介紹以下Enable process。UI上的入口是Settings,撥動Bluetooth開關,就啟動了Bluetooth Enable process,最後由Bluedroid去enable Bluetooth hardware。當Bluetooth hardware enabled,這個enabled訊息會一層層從Bluedroid上傳到UI層,Settings收到這個訊息就可以更新Bluetooth開關的狀態了。具體過程如下圖:

  1. Settings的BluetoothEnabler類(對應於UI上看到的Bluetooth開關),得到代表local device的BluetoothAdapter,再呼叫BluetoothAdapter::enable()。
  2. BluetoothAdapter基本上是個wrapper,不做具體的事情的。它直接呼叫BluetoothManagerService::enable()。
  3. BluetoothManagerService利用Binder機制會去connect AdapterService,最終會導致AdapterService::enable()被呼叫。BluetoothManagerService還會向AdapterService註冊callback函式,用於接收Adapter State Change訊息。
  4. AdapterService維護著一個狀態機AdapterState,所有工作都是通過驅動狀態機來完成的。AdapterState收到AdapterService發過來的USER_TURN_ON訊息,就會呼叫AdapterService::processStart()來啟動Profie Services的初始化和Bluetooth hardware enable process。此時Bluetooth Adapter的狀態是BluetoothAdapter.STATE_TURNING_ON
  5. 每一個profile都有一個service。每個profile service啟動完成後,都會通知AdapterService。當AdapterService::processProfileServiceStateChanged()確認所有的profile services都啟動完成了,就會給狀態機AdapterState發AdapterState.STARTED訊息。
  6. 狀態機AdapterState::PendingCommandState::processMessage()收到AdapterState.STARTED訊息後就立刻呼叫AdapterService::enableNative()。
  7. AdapterService::enableNative()就是用來enable Bluetooth的Bluetooth JNI介面。enableNative()會呼叫Bluetooth HAL的enable()。
  8. Bluedroid用btif_enable_bluetooth()來實現了Bluetooth HAL的enable()。
  9. 當Bluedroid真正完成了enable Bluetooth hardware,就通過btif_enable_bluetooth_evt()中的HAL_CBACK呼叫Bluetooth JNI的adapter_state_change_callback(),這樣就把BT_STATE_ON訊息傳遞給了狀態機AdapterState。
  10. AdapterState會把Bluetooth Adapter的狀態轉換到BluetoothAdapter.STATE_ON,並通過AdapterState::notifyAdapterStateChanged()通知AdapterService。
  11. AdapterService::updateAdapterState()會通過callback函式通知BluetoothManagerService,Adapter狀態改變了。
  12. BluetoothManagerService確認狀態發生了改變就會發出一個BluetoothAdapter.ACTION_STATE_CHANGE的intent。
  13. Settings的BluetoothEnabler收到這個intent之後,就會去更新UI上Bluetooth開關的狀態。
注:以上過程的描述,並不包含這個過程的所有函式呼叫,只是給出了關鍵的函式和狀態。

相關文章