zoukankan      html  css  js  c++  java
  • Bluetooth in Android 4.2 and 4.3(三):Enable Bluetooth

        以下是基于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开关的状态。
    注:以上过程的描述,并不包含这个过程的所有函数调用,只是给出了关键的函数和状态。


  • 相关阅读:
    NYOJ 23 取石子(一)
    XYNUOJ 2026 素数环
    XYNUOJ 1756 魔法工会
    XYNUOJ 1784 胜利大逃亡
    NYOJ 18 The Triangle
    NYOJ 737 合并石子
    XYNUOJ 问题 B: 敌兵布阵
    NYOJ 1063 生活的烦恼
    XYNUOJ 1774 最少拦截系统
    XYNUOJ 1248 排队打水问题
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3233750.html
Copyright © 2011-2022 走看看