当前位置: 首页 > 后端技术 > Java

AndroidBLE蓝牙开发

时间:2023-04-02 00:26:27 Java

AndroidBLE蓝牙开发一:定义传统蓝牙适用于高耗电量的操作,例如Android设备之间的串流和通信。针对有低功耗需求的蓝牙设备,Android4.3(API18)引入了低功耗蓝牙的API,支持应用程序通过这些API进行扫描蓝牙设备、查询服务、读写设备特征(attributecharacteristic)等操作。AndroidBLE使用的蓝牙协议是GATT协议二:AndroidBLEAPI简介1.BluetoothAdapterBluetoothAdapter有基本的蓝牙操作,比如开启蓝牙扫描,使用已知的MAC地址(BluetoothAdapter#getRemoteDevice)实例化一个BluetoothDevice用于连接蓝牙设备操作等。2.BluetoothDevice代表一个远程蓝牙设备。该类允许您连接到所代表的蓝牙设备或获取有关它的一些信息,例如它的名称、地址和绑定状态等。3.BluetoothGatt该类提供了蓝牙GATT的基本功能。比如重新连接蓝牙设备,发现蓝牙设备的服务等。4.通过BluetoothGatt#getService获取BluetoothGattService类。如果当前服务不可见,它将返回一个空值。这个类对应于上面提到的Service。我们可以进一步通过该类的getCharacteristic(UUIDuuid)获取Characteristic,实现蓝牙数据的双向传输。5.BluetoothGattCharacteristic类对应于上述特征。该类定义了需要写入外围设备的数据和读取外围设备发送的数据。三:Android蓝牙开发实例第一步:添加权限第二步:连接蓝牙前初始化在建立蓝牙连接之前,需要确认该设备支持BLE。如果支持,请检查蓝牙是否打开。如果未启用蓝牙,您可以使用BluetoothAdapter类来启用蓝牙。1.获取BluetoothAdapter私有BluetoothAdaptermBluetoothAdapter;/***初始化蓝牙配置*/privatevoidinitBlueTooth(){bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器}获取蓝牙适配器的第二种方式:privateBluetoothAdapterbluetoothAdapter;...finalBluetoothManagerbluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);//通过蓝牙管理器获取适配器bluetoothAdapter=bluetoothManager.getAdapter();BluetoothAdapter表示本地设备的蓝牙适配器。BluetoothAdapter可以执行基本的蓝牙任务,例如启动设备发现、查询配对设备列表、实例化具有已知MAC地址的BluetoothDevice类,以及创建BluetoothServerSocket以侦听来自其他设备的连接请求。查看源码:publicfinalclassBluetoothAdapter{//获取蓝牙适配器publicstaticsynchronizedBluetoothAdaptergetDefaultAdapter(){}//获取蓝牙设备的传入地址publicBluetoothDevicegetRemoteDevice(Stringaddress){}//获取蓝牙状态publicintgetState(){}//蓝牙是否可用publicbooleanisEnabled(){}//获取本地蓝牙名称publicStringgetName(){}//获取本地蓝牙地址publicStringgetAddress(){}//开始扫描搜索publicbooleanstartDiscovery(){}//停止扫描搜索publicbooleancancelDiscovery(){}//获取配对的蓝牙设备publicSetgetBondedDevices(){}//开启蓝牙扫描publicbooleanstartLeScan(LeScanCallbackcallback){returnstartLeScan(空,回调);}//在BluetoothAdapter中,我们可以看到有两种扫描蓝牙的方法。第一种方法可以指定只扫描具有特定UUIDService的蓝牙设备,第二种方法是扫描所有蓝牙设备。publicbooleanstartLeScan(finalUUID[]serviceUuids,finalLeScanCallbackcallback){}等函数2.如果检测到蓝牙没有开启,尝试开启蓝牙if(bluetoothAdapter!=null){//蓝牙是否开启supportedif(bluetoothAdapter.isEnabled()){//打开//开始扫描周围的蓝牙设备,如果扫描到蓝牙设备,则通过广播接收器发送广播if(mAdapter!=null){//当适配器不为空,说明已经有数据了,所以清空list数据,然后扫描list.clear();mAdapter.notifyDataSetChanged();}bluetoothAdapter.startDiscovery();}else{//未开启Intentintent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(意图,REQUEST_ENABLE_BLUETOOTH);}}else{showMsg("您的设备不支持蓝牙");}监听和搜索设备:我们可以自定义一个广播来接收这些系统广播。通过广播接收器查看扫描到的蓝牙设备。设备,系统将发送此广播(BluetoothDevice.ACTION_FOUND)。参数intent可以获得蓝牙设备BluetoothDevice。私有类BluetoothReceiver扩展BroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();switch(action){caseBluetoothDevice.ACTION_FOUND://扫描到设备showDevicesData(context,intent);//数据显示中断;caseBluetoothDevice.ACTION_BOND_STATE_CHANGED://设备绑定状态改变mAdapter.changeBondDevice();//刷新适配器break;caseBluetoothAdapter.ACTION_DISCOVERY_STARTED://开始扫描loadingLay.setVisibility(View.VISIBLE);//显示加载布局break;caseBluetoothAdapter.ACTION_DISCOVERY_FINISHED://扫描完成loadingLay.setVisibility(View.GONE);//隐藏加载布局中断;}}创建监听器广播监听器privatevoidinitBlueTooth(){IntentFilterintentFilter=newIntentFilter();//create创建一个IntentFilter对象intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//获取扫描结果intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态改变intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始扫描intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描结束bluetoothReceiver=newBluetoothReceiver();//实例化广播接收器registerReceiver(bluetoothReceiver,intentFilter);//注册广播接收器bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();//获取Bluetoothadapter}BluetoothDevice表示远程蓝牙设备允许您使用相应的设备创建BluetoothDevice或查询它的名称、地址、类和连接状态等信息。源代码:publicfinalclassBluetoothDeviceimplementsParcelable{publicvoidwriteToParcel(Parcelout,intflags){out.writeString(mAddress);}publicStringgetAddress(){}publicStringgetName(){}}第三步:扫描蓝牙设备外围设备打开蓝牙后,会广播很多设备的数据信息,比如mac地址,uuid和很快。通过这些数据我们可以筛选出需要的设备。在BluetoothAdapter中,我们可以看到有两种扫描蓝牙的方法。第一种方法可以指定只扫描具有特定UUIDService的蓝牙设备,第二种方法是扫描所有蓝牙设备。publicbooleanstartLeScan(finalUUID[]serviceUuids,finalLeScanCallbackcallback){}publicbooleanstartLeScan(LeScanCallbackcallback){returnstartLeScan(null,callback);}//停止蓝牙扫描publicvoidstopLeScan(LeScanCallbackcallback){}implementLeScanCallbackcallbackprivateLeDeviceListAdapterleDeviceListAdapter;...//设备扫描回调.privateBluetoothAdapter.LeScanCallbackleScanCallback=newBluetoothAdapter.LeScanCallback(){@OverridepublicvoidonLeScan(最终的BluetoothDevice设备,intrssi,byte[]scanRec){@Overridepublicvoidrun(){leDeviceListAdapter.addDevice(device);leDeviceListAdapter.notifyDataSetChanged();}});}};//开始扫描mBluetoothAdapter.startLeScan(callback);总结:方法一:startLeScan()方法startLeScan()方法有一个回调参数BluetoothAdapter.LeScanCallback类,首先创建该类的一个对象,当扫描发现周围的蓝牙设备时,会返回onLeScan函数,可以用于onLeScan函数中startLeScan()方法处理逻辑的特点:onLeScan()中不能进行耗时操作,尤其是周围BLE设备较多时,容易造成底层阻塞。方法二:startDiscovery()方法该方法使用广播所以首先定义一个类BluetoothReceiver,让他继承自BroadcastReceiver,并重写onReceive()方法,将扫描到设备时的逻辑写在该方法中。然后创建一个BluetoothReceiver对象,注册广播,然后执行startDiscovery()方法。对于经典蓝牙设备,扫描是通过调用startDiscovery接口,通过BroadcastReceiver接收返回结果,可以获取设备MAC地址、名称和RSSI。startDiscovery是一个异步调用并立即返回。如果不调用cancelDiscovery主动停止扫描,扫描最多需要12s。广播主要监听以下动作:BluetoothDevice.ACTION_FOUNDBluetoothAdapter.ACTION_DISCOVERY_STARTEDBluetoothAdapter.ACTION_DISCOVERY_FINISHED另外需要注意的是,startDiscovery返回的设备不包括配对的设备。要获得配对设备,需要额外调用getBondedDevices。第4步:连接到GATT服务器。连接蓝牙设备与BLE设备交互的第一步是连接到GATT服务器。更具体地说,是与设备上的GATT服务器的连接。要连接到BLE设备上的GATT服务器,请使用connectGatt()方法。该方法采用三个参数:一个Context对象,autoConnect(布尔值,指示是否在可用时自动连接到BLE设备),以及对BluetoothGattCallback的引用:BluetoothGattconnectGatt(Contextcontext,booleanautoConnect,BluetoothGattCallbackcallback)第二个参数指示是否自动需要连接。如果设置为true,表示如果设备断开连接,会继续尝试自动连接。设置为false以仅进行一次连接尝试。第三个参数是连接后一系列操作的回调,比如连接和断开的回调,服务发现的回调,写入数据成功的回调,数据读取成功的回调等等。END:持之以恒,朽木不朽;持之以恒,能雕金石