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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值