鸿蒙应用程序开发 课件 第12章 网络与连接_第1页
鸿蒙应用程序开发 课件 第12章 网络与连接_第2页
鸿蒙应用程序开发 课件 第12章 网络与连接_第3页
鸿蒙应用程序开发 课件 第12章 网络与连接_第4页
鸿蒙应用程序开发 课件 第12章 网络与连接_第5页
已阅读5页,还剩58页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第12章网络与连接引言本章学习目标了解蓝牙开发基本概念了解HarmonyOS网络管理模块常用功能2掌握传统蓝牙的开发方法掌握BLE牙低功耗蓝开发方法熟练打开一个URL链接010203040512.1蓝牙开发概述12.2基于传统蓝牙开发12.3基于BLE低功耗蓝牙开发12.4网络管理开发概述12.5URL链接访问CONTENTS12.1蓝牙开发概述4蓝牙是短距离无线通信的一种方式,支持蓝牙的两个设备必须配对后才能通信。HarmonyOS蓝牙主要分为传统蓝牙和低功耗蓝牙(通常称为BLE,BluetoothLowEnergy)。传统蓝牙指的是蓝牙版本3.0以下的蓝牙,低功耗蓝牙指的是蓝牙版本4.0以上的蓝牙。传统蓝牙01HarmonyOS传统蓝牙提供的功能有:传统蓝牙本机管理和传统蓝牙远端设备操作BLE02BLE外围设备作为服务端,可以接收来自中心设备(客户端)的GATT连接请求,应答来自中心设备的特征值内容读取和写入请求,并向中心设备提供数据。约束与限制03调用蓝牙的打开接口需要USE_BLUETOOTH权限,调用蓝牙扫描接口需要LOCATION权限和DISCOVER_BLUETOOTH权限。010203040512.1蓝牙开发概述12.2基于传统蓝牙开发12.3基于BLE低功耗蓝牙开发12.4网络管理开发概述12.5URL链接访问CONTENTS12.2.1接口说明6蓝牙本机管理类BluetoothHost的主要接口如表所示蓝牙远端设备管理类BluetoothRemoteDevice的主要接口如表所示接口名功能描述getDefaultHost(Contextcontext)获取BluetoothHost实例,去管理本机蓝牙操作。enableBt​()打开本机蓝牙。disableBt​()关闭本机蓝牙。setLocalName​(Stringname)设置本机蓝牙名称。getLocalName​()获取本机蓝牙名称。getBtState​()获取本机蓝牙名称。startBtDiscovery​()获取本机蓝牙名称。cancelBtDiscovery​()取消蓝牙设备扫描。isBtDiscovering​()取消蓝牙设备扫描。getProfileConnState​(intprofile)获取本机蓝牙profile对其他设备的连接状态。getPairedDevices​()获取本机蓝牙已配对的蓝牙设备列。接口名功能描述getDeviceAddr​()获取远端蓝牙设备地址。getDeviceClass​()获取远端蓝牙设备地址。getDeviceName​()获取远端蓝牙设备地址。getPairState​()获取远端设备配对状态。startPair​()获取远端设备配对状态。12.2.2打开本机蓝牙7打开本机蓝牙操作流程如下:调用BluetoothHost的getDefaultHost(Contextcontext)接口,获取BluetoothHost实例,管理本机蓝牙操作。调用enableBt()接口,打开蓝牙。调用getBtState(),查询蓝牙是否打开。//获取蓝牙本机管理对象BluetoothHostbluetoothHost=BluetoothHost.getDefaultHost(context);//调用打开接口bluetoothHost.enableBt();//调用获取蓝牙开关状态接口intstate=bluetoothHost.getBtState();12.2.3向远端设备发起配对8传统蓝牙远端管理操作主要是针对远端蓝牙设备的基本操作,包括获取远端蓝牙设备地址、类型、名称和配对状态,以及向远端设备发起配对。在打开蓝牙并扫描到可用蓝牙设备之后,可以向其发起配对,操作流程如下:调用BluetoothHost的getDefaultHost(Contextcontex)接口,获取BluetoothHost实例,管理本机蓝牙操作。调用enableBt()接口,打开蓝牙。调用startBtDiscovery(),扫描设备。调用startPair(),发起配对。调用getDeviceAddr(),获取远端蓝牙设备地址。12.2.3向远端设备发起配对9调用getDeviceAddr(),获取远端蓝牙设备地址。//获取蓝牙本机管理对象BluetoothHostbluetoothHost=BluetoothHost.getDefaultHost(context);//调用打开接口bluetoothHost.enableBt();//调用扫描接口bluetoothHost.startBtDiscovery();//设置界面会显示出扫描结果列表,点击蓝牙设备去配对BluetoothRemoteDevicedevice=bluetoothHost.getRemoteDev(TEST_ADDRESS);device.startPair();//调用接口获取远端蓝牙设备地址StringdeviceAddr=device.getDeviceAddr();12.2.4案例:传统蓝牙的连接配对10创建一个名为TraditionalBluetoothDemo的应用来演示传统蓝牙的连接配对。在config.json文件中请求权限内容如下:"reqPermissions":[ { "name":"ohos.permission.USE_BLUETOOTH" }, { "name":"ohos.permission.LOCATION" }, { "name":"ohos.permission.DISCOVER_BLUETOOTH" }]12.2.4案例:传统蓝牙的连接配对11其中权限ohos.permission.LOCATION为敏感权限,需要动态申请,在MainAbility文件中申请内容如下:publicclassMainAbilityextendsAbility{@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setMainRoute(MainAbilitySlice.class.getName());if(verifySelfPermission("ohos.permission.LOCATION")!=IBundleManager.PERMISSION_GRANTED){//应用未被授予权限

if(canRequestPermission("ohos.permission.LOCATION")){//是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)requestPermissionsFromUser(newString[]{"ohos.permission.LOCATION"},1);}else{ //显示应用需要权限的理由,提示用户进入设置授权

}}else{ //权限已被授予

}}12.2.4案例:传统蓝牙的连接配对12@OverridepublicvoidonRequestPermissionsFromUserResult(intrequestCode,String[]permissions,int[]grantResults){if(requestCode==1){//匹配requestPermissions的requestCodeif(grantResults.length>0&&grantResults[0]==IBundleManager.PERMISSION_GRANTED){//权限被授予

//注意:因时间差导致接口权限检查时有无权限

//所以对那些因无权限而抛异常的接口进行异常捕获处理

}else{//权限被拒绝

}return;}}}12.2.4案例:传统蓝牙的连接配对13修改MainAbilitySlice文件,其内容如下:publicclassMainAbilitySliceextendsAbilitySlice{//定义日志标签

privatestaticfinalHiLogLabelLABEL_LOG=newHiLogLabel(HiLog.LOG_APP,0x00922,"MainAbilitySlice");//获取蓝牙本机管理对象

privateBluetoothHostbluetoothHost;//待配对的设备地址

privateStringselectedDeviceAddr;@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);//初始化蓝牙

initBluetooth();//初始化组件

initComponent();}12.2.4案例:传统蓝牙的连接配对14//初始化蓝牙

privatevoidinitBluetooth(){HiL(LABEL_LOG,"initBluetooth()方法被调用");bluetoothHost=BluetoothHost.getDefaultHost(getContext());//打开本机蓝牙

bluetoothHost.enableBt();//获取本机蓝牙名称

Optional<String>nameOptional=bluetoothHost.getLocalName();//获取本机蓝牙状态

intstate=bluetoothHost.getBtState();//getBtState()方法返回“2”表示蓝牙已开启

HiL(LABEL_LOG,"本机蓝牙名称为:%{public}s,状态为:%{public}d.",nameOptional.get(),state);}//初始化组件

privatevoidinitComponent(){//找到组件

ButtonButton_Start=findComponentById(ResourceTable.Id_Button_Start);ButtonButton_Pair=findComponentById(ResourceTable.Id_Button_Pair);//给Button_Start添加单击事件

Button_Start.setClickedListener(this::Start);//给Button_Pair添加单击事件

Button_Pair.setClickedListener(this::Pair);}12.2.4案例:传统蓝牙的连接配对15

privatevoidStart(Componentcomponent){//通过MatchingSkills定义需要订阅的事件

MatchingSkills

matchingSkills=newMatchingSkills();//订阅发现远程蓝牙设备时报告事件

matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED);//设置订阅参数

CommonEventSubscribeInfo

subscribeInfo=newCommonEventSubscribeInfo(matchingSkills);

MyCommonEventSubscribersubscriber=newMyCommonEventSubscriber(subscribeInfo);try{ //订阅事件

CommonEventManager.subscribeCommonEvent(subscriber);}catch(RemoteExceptione){HiL(LABEL_LOG,"subscribeCommonEvent调用期间出现异常");}//发起蓝牙设备扫描

bluetoothHost.startBtDiscovery();}12.2.4案例:传统蓝牙的连接配对16privatevoidPair(Componentcomponent){//配对

BluetoothRemoteDevicedevice=bluetoothHost.getRemoteDev(selectedDeviceAddr);//返回ture为配对成功,false为失败

booleanresult=device.startPair();HiL(LABEL_LOG,"最终配对设备地址:%{public}s,result:%{public}s.",selectedDeviceAddr,result);}//接收系统广播,创建CommonEventSubscriber派生类,在onReceiveEvent()回调函数中处理公共事件

classMyCommonEventSubscriberextendsCommonEventSubscriber{publicMyCommonEventSubscriber(CommonEventSubscribeInfosubscribeInfo){super(subscribeInfo);}@OverridepublicvoidonReceiveEvent(CommonEventDatadata){if(data==null){return;}Intentinfo=data.getIntent();if(info==null){return;}12.2.4案例:传统蓝牙的连接配对17 //获取系统广播的actionStringaction=info.getAction();//判断是否为扫描到设备的广播

if(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED.equals(action)){IntentParamsmyParam=info.getParams();BluetoothRemoteDevicedevice=(BluetoothRemoteDevice)myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);//获取远端蓝牙设备地址

StringdeviceAddr=device.getDeviceAddr();//获取远端蓝牙设备名称

Optional<String>deviceNameOptional=device.getDeviceName();StringdeviceName=deviceNameOptional.orElse("");//获取远端设备配对状态

intpairState=device.getPairState();HiL(LABEL_LOG,"远端设备地址:%{public}s"+",远端设备名称:%{public}s"+",远端设备状态:%{public}s.",deviceAddr,deviceName,pairState);//getPairState()方法返回“0”表示远端设备未配对12.2.4案例:传统蓝牙的连接配对18 //可作为待配对设备

if(pairState==0){selectedDeviceAddr=deviceAddr;}}}}@OverrideprotectedvoidonStop(){super.onStop();//取消蓝牙设备扫描

bluetoothHost.cancelBtDiscovery();}@OverridepublicvoidonActive(){super.onActive();}@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);}}12.2.4案例:传统蓝牙的连接配对19上述代码中:初始化本机蓝牙和组件后,在Start()方法中订阅了发现远程蓝牙设备时的报告事件,然后在CommonEventSubscriber派生类的onReceiveEvent()回调函数中处理扫描到的蓝牙设备信息,如:远端设备地址、远端设备名称、远端设备状态,并将其以日志的形式打印出来。在onStop()方法中取消蓝牙设备扫描。打开远程模拟器,打开蓝牙,运行程序,界面显示如图所示。12.2.4案例:传统蓝牙的连接配对20单击扫描按钮,控制台输出内容如下:06-0912:27:43.23822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:initBluetooth()方法被调用06-0912:27:43.25622192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:本机蓝牙名称为:HUAWEIP40,状态为:2.06-0912:29:19.67022192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:B0:55:08:14:9D:7B,远端设备名称:HonorV12,远端设备状态:0.06-0912:29:19.68322192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:20:AB:37:60:31:86,远端设备名称:“Administrator”的iPhone,远端设备状态:0.06-0912:29:19.69222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:50:04:B8:C1:81:F8,远端设备名称:HISIP12PLUS,远端设备状态:0.06-0912:29:19.69822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:1C:15:1F:8B:80:0E,远端设备名称:,远端设备状态:0.06-0912:29:19.70522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:50:04:B8:C1:82:CC,远端设备名称:,远端设备状态:0.06-0912:29:19.71522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:12:B1:F8:0E:B4:7D,远端设备名称:,远端设备状态:0.06-0912:29:19.72222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:0C:8F:FF:FD:49:34,远端设备名称:LOVERLIAN,远端设备状态:0.12.2.4案例:传统蓝牙的连接配对21单击配对按钮,控制台输出内容如下:06-0912:29:19.82522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:30:74:96:55:F5:E3,远端设备名称:honorBand3-5e3,远端设备状态:0.06-0912:29:21.66322192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:20:17:06:22:02:78,远端设备名称:,远端设备状态:0.06-0912:29:21.69222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:43:F1:F2:3B:3B:04,远端设备名称:,远端设备状态:0.06-0912:29:21.70222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:40:96:54:76:07:BB,远端设备名称:,远端设备状态:0.06-0912:29:21.70822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:远端设备地址:40:96:54:76:07:BB,远端设备名称:,远端设备状态:0.06-0912:30:03.18622192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:最终配对设备地址:40:96:54:76:07:BB,result:true.startPair()方法返回为ture,配对成功。010203040512.1蓝牙开发概述12.2基于传统蓝牙开发12.3基于BLE低功耗蓝牙开发12.4网络管理开发概述12.5URL链接访问CONTENTS12.3.1接口说明23BLE中心设备管理类BleCentralManager的主要接口,中心设备管理回调类BleCentralManagerCallback的主要接口,BLE广播相关的BleAdvertiser类和BleAdvertiseCallback类的主要接口如下表所示。BLE中心设备管理类BleCentralManager的主要接口接口名功能描述startScan(List<BleScanFilter>filters)进行BLE蓝牙扫描,并使用filters对结果进行过滤。stopScan()停止BLE蓝牙扫描。getDevicesByStates(int[]states)停止BLE蓝牙扫描。BleCentralManager(Contextcontext,BleCentralManagerCallbackcallback)获取中心设备管理对象。12.3.1接口说明24中心设备管理回调类BleCentralManagerCallback的主要接口BLE广播相关的BleAdvertiser类和BleAdvertiseCallback类的主要接口接口名功能描述scanResultEvent​(BleScanResultresult)扫描到BLE设备的结果回调。groupScanResultsEvent​(List<BleScanResult>scanResults)扫描到一组BLE设备的结果回调。scanFailedEvent​(intresultCode)启动扫描失败的回调。接口名功能描述BleAdvertiser(Contextcontext,BleAdvertiseCallbackcallback)用于获取广播操作对象。startAdvertising(BleAdvertiseSettingssettings,BleAdvertiseDataadvData,BleAdvertiseDatascanResponse)进行BLE广播,第一个参数为广播参数,第二个为广播数据,第三个参数是扫描和广播数据参数的响应。stopAdvertising()停止BLE广播。startResultEvent(intresult)广播回调结果。12.3.2BLE扫描及广播25中心设备进行BLE扫描操作流程如下:进行BLE扫描之前先要继承BleCentralManagerCallback类实现scanResultEvent和scanFailedEvent回调函数,用于接收扫描结果。调用BleCentralManager(BleCentralManagerCallbackcallback)接口获取中心设备管理对象。获取扫描过滤器,过滤器为空时为不使用过滤器扫描,然后调用startScan()开始扫描BLE设备,在回调中获取扫描到的BLE设备。示例代码如下://实现扫描回调publicclassScanCallbackimplementsBleCentralManagerCallback{List<BleScanResult>results=newArrayList<BleScanResult>();@OverridepublicvoidscanResultEvent(BleScanResultresultCode){//对扫描结果进行处理

results.add(resultCode);}12.3.2BLE扫描及广播26获取扫描过滤器,过滤器为空时为不使用过滤器扫描,然后调用startScan()开始扫描BLE设备,在回调中获取扫描到的BLE设备。示例代码如下:@OverridepublicvoidscanFailedEvent(intresultCode){HiLog.warn(TAG,"StartScanfailed,Code:%{public}d",resultCode);}@OverridepublicvoidgroupScanResultsEvent(finalList<BleScanResult>scanResults){//对扫描结果进行处理

}}//获取中心设备管理对象privateScanCallbackcentralManagerCallback=newScanCallback();privateBleCentralManagercentralManager=newBleCentralManager(context,centralManagerCallback);//创建扫描过滤器然后开始扫描List<BleScanFilter>filters=newArrayList<BleScanFilter>();centralManager.startScan(filters);12.3.2BLE扫描及广播27外围设备进行BLE广播操作流程如下:进行BLE广播前需要先继承advertiseCallback类实现startResultEvent回调,用于获取广播结果。调用接口BleAdvertiser(Contextcontext,BleAdvertiseCallbackcallback)获取广播对象,构造广播参数和广播数据。调用startAdvertising(BleAdvertiseSettingssettings,BleAdvertiseDataadvData,BleAdvertiseDatascanResponse)接口开始BLE广播。示例代码如下://实现BLE广播回调privateBleAdvertiseCallbackadvertiseCallback=newBleAdvertiseCallback(){@OverridepublicvoidstartResultEvent(intresult){if(result==BleAdvertiseCallback.RESULT_SUCC){//开始BLE广播成功

}else{//开始BLE广播失败

}}}12.3.2BLE扫描及广播28//获取BLE广播对象privateBleAdvertiseradvertiser=newBleAdvertiser(this,advertiseCallback);//创建BLE广播参数和数据privateBleAdvertiseDatadata=newBleAdvertiseData.Builder() //添加服务的UUID .addServiceUuid(SequenceUuid.uuidFromString(Server_UUID)) //添加广播数据内容 .addServiceData(SequenceUuid.uuidFromString(Server_UUID),newbyte[]{0x12}).build();privateBleAdvertiseSettingsadvertiseSettings=newBleAdvertiseSettings.Builder() //设置是否可连接广播 .setConnectable(true) //设置广播间隔 .setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT) //设置广播功率 .setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT) .build();//开始广播advertiser.startAdvertising(advertiseSettings,data,null);12.3.3案例:BLE蓝牙的扫描与广播29创建一个名为BleDemo的应用来演示BLE蓝牙中心设备扫描外围设备和外围设备向中心设备发出广播。调用蓝牙的打开接口及调用蓝牙扫描接口需要申请权限,所以在config.json文件中请求权限内容如下:"reqPermissions":[{"name":"ohos.permission.USE_BLUETOOTH"},{"name":"ohos.permission.DISCOVER_BLUETOOTH"},{"name":"ohos.permission.LOCATION"},{"name":"ohos.permission.MANAGE_BLUETOOTH"}]12.3.3案例:BLE蓝牙的扫描与广播30其中权限ohos.permission.LOCATION为敏感权限,需要动态申请,在MainAbility文件中申请内容如下:publicclassMainAbilityextendsAbility{@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setMainRoute(MainAbilitySlice.class.getName());if(verifySelfPermission("ohos.permission.LOCATION")!=IBundleManager.PERMISSION_GRANTED){//应用未被授予权限if(canRequestPermission("ohos.permission.LOCATION")){//是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)requestPermissionsFromUser(newString[]{"ohos.permission.LOCATION"},1);}else{//显示应用需要权限的理由,提示用户进入设置授权}}else{//权限已被授予}}12.3.3案例:BLE蓝牙的扫描与广播31

@OverridepublicvoidonRequestPermissionsFromUserResult(intrequestCode,String[]permissions,int[]grantResults){if(requestCode==1){//匹配requestPermissions的requestCodeif(grantResults.length>0&&grantResults[0]==IBundleManager.PERMISSION_GRANTED){//权限被授予

//注意:因时间差导致接口权限检查时有无权限

//所以对那些因无权限而抛异常的接口进行异常捕获处理

}else{//权限被拒绝

}return;}}}12.3.3案例:BLE蓝牙的扫描与广播32修改MainAbilitySlice文件,其内容如下:publicclassMainAbilitySliceextendsAbilitySlice{//定义日志标签privatestaticfinalHiLogLabelLABEL_LOG=newHiLogLabel(HiLog.LOG_APP,0x00922,"MainAbilitySlice");//获取中心设备管理对象privateBleCentralManagerbleCentralManager;//获取BLE广播对象privateBleAdvertiserbleAdvertiser;//获取BLE广播数据对象privateBleAdvertiseDatableAdvertiseData;//获取BLE广播参数对象privateBleAdvertiseSettingsbleAdvertiseSettings;//随机生成UUIDprivateUUIDServer_UUID=UUID.randomUUID();//连接状态privatestaticfinalint[]STATES={ProfileBase.STATE_DISCONNECTED,ProfileBase.STATE_CONNECTING,ProfileBase.STATE_CONNECTED,ProfileBase.STATE_DISCONNECTING,};12.3.3案例:BLE蓝牙的扫描与广播33

@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);//初始化蓝牙initBluetooth();//初始化组件initComponent();}

//初始化蓝牙privatevoidinitBluetooth(){HiL(LABEL_LOG,"initBluetooth()方法被调用");//获取中心设备管理回调类对象ScanCallbackcentralManagerCallback=newScanCallback();//获取中心设备管理对象bleCentralManager=newBleCentralManager(getContext(),centralManagerCallback);bleAdvertiser=newBleAdvertiser(this,advertiseCallback);

12.3.3案例:BLE蓝牙的扫描与广播34 //创建BLE广播数据

bleAdvertiseData=newBleAdvertiseData.Builder()//添加服务的UUID.addServiceUuid(SequenceUuid.uuidFromString(String.valueOf(Server_UUID)))//添加广播数据内容

.addServiceData(SequenceUuid.uuidFromString(String.valueOf(Server_UUID)),newbyte[]{0x11}).build();//创建BLE广播参数

bleAdvertiseSettings=newBleAdvertiseSettings.Builder()//设置是否可连接广播

.setConnectable(true)//设置广播间隔

.setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT)//设置广播功率

.setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT).build();}12.3.3案例:BLE蓝牙的扫描与广播35 //初始化组件

privatevoidinitComponent(){ HiL(LABEL_LOG,"initComponent()方法被调用"); //找到组件

ButtonButton_Start=findComponentById(ResourceTable.Id_Button_Start); ButtonButton_Advertise=findComponentById(ResourceTable.Id_Button_Advertise); //给Button_Start添加单击事件

Button_Start.setClickedListener(this::Start); //给Button_Advertise添加单击事件

Button_Advertise.setClickedListener(this::Advertise); } privatevoidStart(Componentcomponent){ HiL(LABEL_LOG,"开始扫描") //创建扫描过滤器开始扫描

List<BleScanFilter>filters=newArrayList<>(); //进行BLE蓝牙扫描,并使用filters对结果进行过滤。

bleCentralManager.startScan(filters);

12.3.3案例:BLE蓝牙的扫描与广播36 //返回与指定状态匹配的BlePeripheralDevice列表。

List<BlePeripheralDevice>devices=bleCentralManager.getDevicesByStaSTATES);for(BlePeripheralDevicedevice:devices){//获取BLE外围设备名

Optional<String>deviceNameOptional=device.getDeviceName();StringdeviceName=deviceNameOptional.orElse("");//获取BLE外围设备地址

StringdeviceAddr=device.getDeviceAddr();HiL(LABEL_LOG,"BLE外围设备名:%{public}s"+",BLE外围设备地址:%{public}s.",deviceName,deviceAddr);}}privatevoidAdvertise(Componentcomponent){HiL(LABEL_LOG,"开始广播");//开始广播

bleAdvertiser.startAdvertising(bleAdvertiseSettings,bleAdvertiseData,null);}12.3.3案例:BLE蓝牙的扫描与广播37 //实现扫描回调classScanCallbackimplementsBleCentralManagerCallback{List<BleScanResult>results=newArrayList<BleScanResult>();

@OverridepublicvoidscanResultEvent(BleScanResultresultCode){//对扫描结果进行处理results.add(resultCode);}

@OverridepublicvoidscanFailedEvent(intresultCode){

}

@OverridepublicvoidgroupScanResultsEvent(List<BleScanResult>list){

}}

12.3.3案例:BLE蓝牙的扫描与广播38 //实现BLE广播回调BleAdvertiseCallbackadvertiseCallback=newBleAdvertiseCallback(){@OverridepublicvoidstartResultEvent(intresult){if(result==BleAdvertiseCallback.RESULT_SUCC){HiL(LABEL_LOG,"广播成功!");}else{HiL(LABEL_LOG,"广播失败!");}}};

@OverridepublicvoidonActive(){super.onActive();}

@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);}}12.3.3案例:BLE蓝牙的扫描与广播39打开远程模拟器,运行程序,应用初始页面如图所示。单击扫描按钮,控制台输出内容如下:06-0913:05:09.44417377-17377/com.example.bledemoI00922/MainAbilitySlice:initBluetooth()方法被调用06-0913:05:09.45217377-17377/com.example.bledemoI00922/MainAbilitySlice:initComponent()方法被调用06-0913:06:46.02817377-17377/com.example.bledemoI00922/MainAbilitySlice:开始扫描010203040512.1蓝牙开发概述12.2基于传统蓝牙开发12.3基于BLE低功耗蓝牙开发12.4网络管理开发概述12.5URL链接访问CONTENTS12.4网络管理开发概述41HarmonyOS网络管理模块主要提供以下功能:数据连接管理:网卡绑定,打开URL,数据链路参数查询。数据网络管理:指定数据网络传输,获取数据网络状态变更,数据网络状态查询。使用网络管理模块的相关功能时,需要请求相应的权限。如下表所示:权限名权限描述ohos.permission.GET_NETWORK_INFO获取网络连接信息。ohos.permission.SET_NETWORK_INFO修改网络连接状态。ohos.permission.INTERNET允许程序打开网络套接字,进行网络连接。010203040512.1蓝牙开发概述12.2基于传统蓝牙开发12.3基于BLE低功耗蓝牙开发12.4网络管理开发概述12.5URL链接访问CONTENTS12.5.1接口说明43URL链接访问,所使用的接口如下表所示类名接口名功能描述NetManagergetInstance(Contextcontext)获取网络管理的实例对象。hasDefaultNet()查询当前是否有默认可用的数据网络。getDefaultNet()获取当前默认的数据网络句柄。addDefaultNetStatusCallback(NetStatusCallbackcallback)获取当前默认的数据网络状态变化。setAppNet(NetHandlenetHandle)应用绑定该数据网络。NetHandleopenConnection(URLurl,.Proxyproxy)throwsIOException使用该网络打开一个URL链接。12.5.2开发步骤44调用NetManager.getInstance(Context)获取网络管理的实例对象。调用NetManager.getDefaultNet()获取默认的数据网络。调用NetHandle.openConnection()打开一个URL。通过URL链接实例访问网站。示例代码如下:NetManagernetManager=NetManager.getInstance(context);if(!netManager.hasDefaultNet()){return;}NetHandlenetHandle=netManager.getDefaultNet();//可以获取网络状态的变化NetStatusCallbackcallback=newNetStatusCallback(){//重写需要获取的网络状态变化的override函数};netManager.addDefaultNetStatusCallback(callback);12.5.2开发步骤45//通过openConnection来获取URLConnectionHttpURLConnectionconnection=null;try{StringurlString="EXAMPLE_URL";//开发者根据实际情况自定义EXAMPLE_URLURLurl=newURL(urlString);URLConnectionurlConnectionnetHandle.openConnection(url,.Proxy.NO_PROXY);if(urlConnectioninstanceofHttpURLConnection){connection=(HttpURLConnection)urlConnection;connection.setRequestMethod("GET");connection.connect();//之后可进行url的其他操作}}catch(IOExceptione){HiLog.error(TAG,"exceptionhappened.");}finally{if(connection!=null){connection.disconnect();}}12.5.3案例:URL链接访问46创建一个名为URLAccessDemo的应用来演示在手机中打开一个URL链接并将链接中的文本信息渲染在屏幕上。"deviceConfig":{"default":{"directLaunch":false,"network":{"cleartextTraffic":true}}}使用网络管理模块的相关功能时,需要请求相应的权限,且由于HarmonyOS默认支持HTTPS协议,若要使用HTTP协议,需要在config.json中进行配置。使用HTTP协议需进行如下配置:12.5.3案例:URL链接访问47"reqPermissions":[{ "name":"ohos.permission.GET_NETWORK_INFO"},{ "name":"ohos.permission.SET_NETWORK_INFO"},{ "name":"ohos.permission.INTERNET"}]使用网络管理模块的相关功能需要请求如下权限:12.5.3案例:URL链接访问48创建一个名为HttpRequestUtil的工具类,用户只需要提供URL即可完成请求工作,修改其容如下:publicclassHttpRequestUtil{privatestaticStringsendRequest(Contextcontext,StringurlString,Stringmethod,Stringtoken,Stringdata){//返回结果Stringresult=null;//获取网络管理的实例对象NetManagernetManager=NetManager.getInstance(context);//如果默认数据网络没有被激活,则返回if(!netManager.hasDefaultNet()){returnnull;}//获取默认的数据网络NetHandlenetHandle=netManager.getDefaultNet();//可以获取网络状态的变化NetStatusCallbackcallback=newNetStatusCallback(){//重写需要获取的网络状态变化的override函数};netManager.addDefaultNetStatusCallback(callback);12.5.3案例:URL链接访问49 //通过openConnection来获取URLConnectionHttpURLConnectionconnection=null;try{URLurl=newURL(urlString);//获取与给定url匹配的URLConnection对象URLConnectionurlConnection=netHandle.openConnection(url,.Proxy.NO_PROXY);

if(urlConnectioninstanceofHttpURLConnection){connection=(HttpURLConnection)urlConnection;//设置请求方式,这里为GETconnection.setRequestMethod(method);//如果通过请求体传递参数到服务端接口,需要对connection进行额外的设置if(data!=null){//允许通过此网络连接向服务端写数据connection.setDoOutput(true);//设置请求头connection.setRequestProperty("Content-Type","application/json;Charset=utf-8");}12.5.3案例:URL链接访问50 //如果参数token!=null,则需要将token设置到请求头if(token!=null){connection.setRequestProperty("token",token);}//发送请求建立连接connection.connect();

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论