Bluetooth in Android 4.2 and 4.3(三):Enable Bluetooth

來源:互聯網
上載者:User

    以下是基於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開關的狀態。
註:以上過程的描述,並不包含這個過程的所有函數調用,只是給出了關鍵的函數和狀態。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.