Chinaunix首页 | 论坛 | 博客
  • 博客访问: 852360
  • 博文数量: 189
  • 博客积分: 4310
  • 博客等级: 上校
  • 技术积分: 1925
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-27 08:56
文章分类

全部博文(189)

文章存档

2015年(1)

2013年(2)

2012年(1)

2011年(39)

2010年(98)

2009年(48)

分类: LINUX

2011-08-15 19:41:58

[color=darkblue][/color][size=medium][/size] 
BluetoothService里定义的Native方法都在android_server_BluetoothServer.cpp里建立jni调用 
开启 

由BluetoothEnabler控制,在构造里会先调用 LocalBluetoothManager.getInstance(context),在getInstance里会调用init()函数,BluetoothAdapter.getDefaultAdapter()获得蓝牙设备的句柄,如果当前没有蓝牙设备则返回null。 

初始化完毕会监听checkbox的状态,当点击checkbox会调用 LocalBluetoothManager.setBluetoothEnabled(enable)函数。调用mAdapter.enable()到 BluetoothService.enable()开启EnableThread线程,进行打开操作,同时调到 CachedBluetoothDeviceManager.onBluetoothStateChanged来读取上次关闭之前搜索到device. 

涉及到的类: 

BluetoothService(最主要的类,开启具体命令的线程进行enadble,disable等操作) 

LocalBluetoothManager(初始化BluetoothAdapter) 

BluetoothEnabler(界面的点击和状态文字的显示) 

BluetoothAdapter(建立LocalBluetoothManager和BluetoothService的映射关系,主要是通过它调用BluetoothService的函数) 
扫描 

在BluetoothSetting里触发点击,调用LocalBluetoothManager.startScanning(true)函数,通过BluetoothAdapter的startDiscovery调用到BluetoothService里的startDiscovery来调用Native函数 startDiscoveryNative()。 

startDiscovery()是个异步函数,会立即返回,通过注册 ACTION_DISCOVERY_STARTED、ACTION_DISCOVERY_FINISHED、ACTION_FOUND,来确定当前的状态。 

当蓝牙由disable变成enable时会调用扫描,当距离上次扫描超过5分钟的前提下,退出页面,再进到页面的时候也会启动扫描。 

在启动scan的时候,还会判断当前是否在播放音乐,如果在播放音乐,则不启动扫描。 

点击查找设备后,会把设备列表里没有配对的设备清除掉,保留配对状态的设备。 

扫描的过程是一个很耗费资源的过程,在扫描过程,不会去尝试进行新的连接,扫描时间默认是12秒,它是以一个系统服务的形式存在的,可以调用cancelDiscovery()来取消扫描。 
连接 

在setting界面点击连接,会调到CachedBluetoothDevice类的connect方法,调用 updateProfiles(),根据搜索到的device的uuid来向ProfilesList里添加profile,然后遍历 ProfileList,根据不同的profile来获得profileManager。 

然后判断当前的device的Priority,如果Priority=100,则去调用queueCommand(new BluetoothJob(BluetoothCommand.CONNECT, this, profile)),去发送连接的命令。如果Priority=1,则不去自动连接。Priority=-1,代表当前的device没有配对。 

在queueCommand()函数里,有一个消息队列来处理命令,在这里生成了一个BluetoothJob的实例,来代表要执行的命令。 

最终调到processCommand(BluetoothJob job)函数,由它来通过job.command来调用CONNECT: DISCONNECT:REMOVE_BOND: 

以A2DP为例,在connectInt里,根据不同的profile来获得profilemanger,然后调用 profilemanger.connect()函数,在这个函数里调用了BluetoothA2dpService的connectSink()函数,最后调到Native方法connectSinkNative()去建立连接。 

涉及到的一些类: 

CachedBluetoothDevice(搜索到的设备) 

BluetoothDevice(设备类) 

LocalBluetoothProfileManager(各种ProfileManger,实例化各种Profile的service) 

SettingsBtStatus(蓝牙的状态类) 

BluetoothA2dp(为LocalBluetoothProfileManager和BluetoothA2dpService建立映射关系) 

BluetoothA2dpService(最终的服务类,由它调用连接、断开等Native函数,和底层通信)
阅读(2601) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~