Android4.2和4.3中enable bluetooth

轉一篇寫的比較好的BT enable 過程的文章。


以下是基於Android 4.2代碼,對Bluetooth BR/EDR Enableprocess的分析。BluetoothAdapter類代表的是local device Bluetoothadapter,而BluetoothDevice類代表的是remote Bluetooth device。在Android4.3中引入了一個新的類BluetoothManager,它是一個high level manager,被用於”to obtainan instance of an BluetoothAdapter and conduct overall BluetoothManagement“。


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




  1. Settings的BluetoothEnabler類(對應於UI上看到的Bluetooth開關),得到代表localdevice的BluetoothAdapter,再調用BluetoothAdapter::enable()。
  2. BluetoothAdapter基本上是個wrapper,不做具體的事情的。它直接調用BluetoothManagerService::enable()。
  3. BluetoothManagerService利用Binder機制會去connectAdapterService,最終會導致AdapterService::enable()被調用。BluetoothManagerService還會向AdapterService註冊callback函數,用於接收AdapterState Change消息。
  4. AdapterService維護着一個狀態機AdapterState,所有工作都是通過驅動狀態機來完成的。AdapterState收到AdapterService發過來的USER_TURN_ON消息,就會調用AdapterService::processStart()來啓動ProfieServices的初始化和Bluetooth hardware enable process。此時BluetoothAdapter的狀態是BluetoothAdapter.STATE_TURNING_ON
  5. 每一個profile都有一個service。每個profileservice啓動完成後,都會通知AdapterService。當AdapterService::processProfileServiceStateChanged()確認所有的profileservices都啓動完成了,就會給狀態機AdapterState發AdapterState.STARTED消息。
  6. 狀態機AdapterState::PendingCommandState::processMessage()收到AdapterState.STARTED消息後就立刻調用AdapterService::enableNative()。
  7. AdapterService::enableNative()就是用來enable Bluetooth的BluetoothJNI接口。enableNative()會調用Bluetooth HAL的enable()。
  8. Bluedroid用btif_enable_bluetooth()來實現了BluetoothHAL的enable()。
  9. 當Bluedroid真正完成了enable Bluetoothhardware,就通過btif_enable_bluetooth_evt()中的HAL_CBACK調用BluetoothJNI的adapter_state_change_callback(),這樣就把BT_STATE_ON消息傳遞給了狀態機AdapterState。
  10. AdapterState會把BluetoothAdapter的狀態轉換到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開關的狀態。
再貼出圖片,方便後面看。


注:以上過程的描述,並不包含這個過程的所有函數調用,只是給出了關鍵的函數和狀態。

From : http://blog.sina.com.cn/s/blog_69b5d2a50101f52r.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章