鴻蒙應(yīng)用程序開發(fā) 課件 第12章 網(wǎng)絡(luò)與連接_第1頁
鴻蒙應(yīng)用程序開發(fā) 課件 第12章 網(wǎng)絡(luò)與連接_第2頁
鴻蒙應(yīng)用程序開發(fā) 課件 第12章 網(wǎng)絡(luò)與連接_第3頁
鴻蒙應(yīng)用程序開發(fā) 課件 第12章 網(wǎng)絡(luò)與連接_第4頁
鴻蒙應(yīng)用程序開發(fā) 課件 第12章 網(wǎng)絡(luò)與連接_第5頁
已閱讀5頁,還剩58頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

第12章網(wǎng)絡(luò)與連接引言本章學(xué)習(xí)目標(biāo)了解藍牙開發(fā)基本概念了解HarmonyOS網(wǎng)絡(luò)管理模塊常用功能2掌握傳統(tǒng)藍牙的開發(fā)方法掌握BLE牙低功耗藍開發(fā)方法熟練打開一個URL鏈接010203040512.1藍牙開發(fā)概述12.2基于傳統(tǒng)藍牙開發(fā)12.3基于BLE低功耗藍牙開發(fā)12.4網(wǎng)絡(luò)管理開發(fā)概述12.5URL鏈接訪問CONTENTS12.1藍牙開發(fā)概述4藍牙是短距離無線通信的一種方式,支持藍牙的兩個設(shè)備必須配對后才能通信。HarmonyOS藍牙主要分為傳統(tǒng)藍牙和低功耗藍牙(通常稱為BLE,BluetoothLowEnergy)。傳統(tǒng)藍牙指的是藍牙版本3.0以下的藍牙,低功耗藍牙指的是藍牙版本4.0以上的藍牙。傳統(tǒng)藍牙01HarmonyOS傳統(tǒng)藍牙提供的功能有:傳統(tǒng)藍牙本機管理和傳統(tǒng)藍牙遠端設(shè)備操作BLE02BLE外圍設(shè)備作為服務(wù)端,可以接收來自中心設(shè)備(客戶端)的GATT連接請求,應(yīng)答來自中心設(shè)備的特征值內(nèi)容讀取和寫入請求,并向中心設(shè)備提供數(shù)據(jù)。約束與限制03調(diào)用藍牙的打開接口需要USE_BLUETOOTH權(quán)限,調(diào)用藍牙掃描接口需要LOCATION權(quán)限和DISCOVER_BLUETOOTH權(quán)限。010203040512.1藍牙開發(fā)概述12.2基于傳統(tǒng)藍牙開發(fā)12.3基于BLE低功耗藍牙開發(fā)12.4網(wǎng)絡(luò)管理開發(fā)概述12.5URL鏈接訪問CONTENTS12.2.1接口說明6藍牙本機管理類BluetoothHost的主要接口如表所示藍牙遠端設(shè)備管理類BluetoothRemoteDevice的主要接口如表所示接口名功能描述getDefaultHost(Contextcontext)獲取BluetoothHost實例,去管理本機藍牙操作。enableBt?()打開本機藍牙。disableBt?()關(guān)閉本機藍牙。setLocalName?(Stringname)設(shè)置本機藍牙名稱。getLocalName?()獲取本機藍牙名稱。getBtState?()獲取本機藍牙名稱。startBtDiscovery?()獲取本機藍牙名稱。cancelBtDiscovery?()取消藍牙設(shè)備掃描。isBtDiscovering?()取消藍牙設(shè)備掃描。getProfileConnState?(intprofile)獲取本機藍牙profile對其他設(shè)備的連接狀態(tài)。getPairedDevices?()獲取本機藍牙已配對的藍牙設(shè)備列。接口名功能描述getDeviceAddr?()獲取遠端藍牙設(shè)備地址。getDeviceClass?()獲取遠端藍牙設(shè)備地址。getDeviceName?()獲取遠端藍牙設(shè)備地址。getPairState?()獲取遠端設(shè)備配對狀態(tài)。startPair?()獲取遠端設(shè)備配對狀態(tài)。12.2.2打開本機藍牙7打開本機藍牙操作流程如下:調(diào)用BluetoothHost的getDefaultHost(Contextcontext)接口,獲取BluetoothHost實例,管理本機藍牙操作。調(diào)用enableBt()接口,打開藍牙。調(diào)用getBtState(),查詢藍牙是否打開。//獲取藍牙本機管理對象BluetoothHostbluetoothHost=BluetoothHost.getDefaultHost(context);//調(diào)用打開接口bluetoothHost.enableBt();//調(diào)用獲取藍牙開關(guān)狀態(tài)接口intstate=bluetoothHost.getBtState();12.2.3向遠端設(shè)備發(fā)起配對8傳統(tǒng)藍牙遠端管理操作主要是針對遠端藍牙設(shè)備的基本操作,包括獲取遠端藍牙設(shè)備地址、類型、名稱和配對狀態(tài),以及向遠端設(shè)備發(fā)起配對。在打開藍牙并掃描到可用藍牙設(shè)備之后,可以向其發(fā)起配對,操作流程如下:調(diào)用BluetoothHost的getDefaultHost(Contextcontex)接口,獲取BluetoothHost實例,管理本機藍牙操作。調(diào)用enableBt()接口,打開藍牙。調(diào)用startBtDiscovery(),掃描設(shè)備。調(diào)用startPair(),發(fā)起配對。調(diào)用getDeviceAddr(),獲取遠端藍牙設(shè)備地址。12.2.3向遠端設(shè)備發(fā)起配對9調(diào)用getDeviceAddr(),獲取遠端藍牙設(shè)備地址。//獲取藍牙本機管理對象BluetoothHostbluetoothHost=BluetoothHost.getDefaultHost(context);//調(diào)用打開接口bluetoothHost.enableBt();//調(diào)用掃描接口bluetoothHost.startBtDiscovery();//設(shè)置界面會顯示出掃描結(jié)果列表,點擊藍牙設(shè)備去配對BluetoothRemoteDevicedevice=bluetoothHost.getRemoteDev(TEST_ADDRESS);device.startPair();//調(diào)用接口獲取遠端藍牙設(shè)備地址StringdeviceAddr=device.getDeviceAddr();12.2.4案例:傳統(tǒng)藍牙的連接配對10創(chuàng)建一個名為TraditionalBluetoothDemo的應(yīng)用來演示傳統(tǒng)藍牙的連接配對。在config.json文件中請求權(quán)限內(nèi)容如下:"reqPermissions":[ { "name":"ohos.permission.USE_BLUETOOTH" }, { "name":"ohos.permission.LOCATION" }, { "name":"ohos.permission.DISCOVER_BLUETOOTH" }]12.2.4案例:傳統(tǒng)藍牙的連接配對11其中權(quán)限ohos.permission.LOCATION為敏感權(quán)限,需要動態(tài)申請,在MainAbility文件中申請內(nèi)容如下:publicclassMainAbilityextendsAbility{@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setMainRoute(MainAbilitySlice.class.getName());if(verifySelfPermission("ohos.permission.LOCATION")!=IBundleManager.PERMISSION_GRANTED){//應(yīng)用未被授予權(quán)限

if(canRequestPermission("ohos.permission.LOCATION")){//是否可以申請彈框授權(quán)(首次申請或者用戶未選擇禁止且不再提示)requestPermissionsFromUser(newString[]{"ohos.permission.LOCATION"},1);}else{ //顯示應(yīng)用需要權(quán)限的理由,提示用戶進入設(shè)置授權(quán)

}}else{ //權(quán)限已被授予

}}12.2.4案例:傳統(tǒng)藍牙的連接配對12@OverridepublicvoidonRequestPermissionsFromUserResult(intrequestCode,String[]permissions,int[]grantResults){if(requestCode==1){//匹配requestPermissions的requestCodeif(grantResults.length>0&&grantResults[0]==IBundleManager.PERMISSION_GRANTED){//權(quán)限被授予

//注意:因時間差導(dǎo)致接口權(quán)限檢查時有無權(quán)限

//所以對那些因無權(quán)限而拋異常的接口進行異常捕獲處理

}else{//權(quán)限被拒絕

}return;}}}12.2.4案例:傳統(tǒng)藍牙的連接配對13修改MainAbilitySlice文件,其內(nèi)容如下:publicclassMainAbilitySliceextendsAbilitySlice{//定義日志標(biāo)簽

privatestaticfinalHiLogLabelLABEL_LOG=newHiLogLabel(HiLog.LOG_APP,0x00922,"MainAbilitySlice");//獲取藍牙本機管理對象

privateBluetoothHostbluetoothHost;//待配對的設(shè)備地址

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

initBluetooth();//初始化組件

initComponent();}12.2.4案例:傳統(tǒng)藍牙的連接配對14//初始化藍牙

privatevoidinitBluetooth(){HiL(LABEL_LOG,"initBluetooth()方法被調(diào)用");bluetoothHost=BluetoothHost.getDefaultHost(getContext());//打開本機藍牙

bluetoothHost.enableBt();//獲取本機藍牙名稱

Optional<String>nameOptional=bluetoothHost.getLocalName();//獲取本機藍牙狀態(tài)

intstate=bluetoothHost.getBtState();//getBtState()方法返回“2”表示藍牙已開啟

HiL(LABEL_LOG,"本機藍牙名稱為:%{public}s,狀態(tài)為:%{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案例:傳統(tǒng)藍牙的連接配對15

privatevoidStart(Componentcomponent){//通過MatchingSkills定義需要訂閱的事件

MatchingSkills

matchingSkills=newMatchingSkills();//訂閱發(fā)現(xiàn)遠程藍牙設(shè)備時報告事件

matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED);//設(shè)置訂閱參數(shù)

CommonEventSubscribeInfo

subscribeInfo=newCommonEventSubscribeInfo(matchingSkills);

MyCommonEventSubscribersubscriber=newMyCommonEventSubscriber(subscribeInfo);try{ //訂閱事件

CommonEventManager.subscribeCommonEvent(subscriber);}catch(RemoteExceptione){HiL(LABEL_LOG,"subscribeCommonEvent調(diào)用期間出現(xiàn)異常");}//發(fā)起藍牙設(shè)備掃描

bluetoothHost.startBtDiscovery();}12.2.4案例:傳統(tǒng)藍牙的連接配對16privatevoidPair(Componentcomponent){//配對

BluetoothRemoteDevicedevice=bluetoothHost.getRemoteDev(selectedDeviceAddr);//返回ture為配對成功,false為失敗

booleanresult=device.startPair();HiL(LABEL_LOG,"最終配對設(shè)備地址:%{public}s,result:%{public}s.",selectedDeviceAddr,result);}//接收系統(tǒng)廣播,創(chuàng)建CommonEventSubscriber派生類,在onReceiveEvent()回調(diào)函數(shù)中處理公共事件

classMyCommonEventSubscriberextendsCommonEventSubscriber{publicMyCommonEventSubscriber(CommonEventSubscribeInfosubscribeInfo){super(subscribeInfo);}@OverridepublicvoidonReceiveEvent(CommonEventDatadata){if(data==null){return;}Intentinfo=data.getIntent();if(info==null){return;}12.2.4案例:傳統(tǒng)藍牙的連接配對17 //獲取系統(tǒng)廣播的actionStringaction=info.getAction();//判斷是否為掃描到設(shè)備的廣播

if(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED.equals(action)){IntentParamsmyParam=info.getParams();BluetoothRemoteDevicedevice=(BluetoothRemoteDevice)myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);//獲取遠端藍牙設(shè)備地址

StringdeviceAddr=device.getDeviceAddr();//獲取遠端藍牙設(shè)備名稱

Optional<String>deviceNameOptional=device.getDeviceName();StringdeviceName=deviceNameOptional.orElse("");//獲取遠端設(shè)備配對狀態(tài)

intpairState=device.getPairState();HiL(LABEL_LOG,"遠端設(shè)備地址:%{public}s"+",遠端設(shè)備名稱:%{public}s"+",遠端設(shè)備狀態(tài):%{public}s.",deviceAddr,deviceName,pairState);//getPairState()方法返回“0”表示遠端設(shè)備未配對12.2.4案例:傳統(tǒng)藍牙的連接配對18 //可作為待配對設(shè)備

if(pairState==0){selectedDeviceAddr=deviceAddr;}}}}@OverrideprotectedvoidonStop(){super.onStop();//取消藍牙設(shè)備掃描

bluetoothHost.cancelBtDiscovery();}@OverridepublicvoidonActive(){super.onActive();}@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);}}12.2.4案例:傳統(tǒng)藍牙的連接配對19上述代碼中:初始化本機藍牙和組件后,在Start()方法中訂閱了發(fā)現(xiàn)遠程藍牙設(shè)備時的報告事件,然后在CommonEventSubscriber派生類的onReceiveEvent()回調(diào)函數(shù)中處理掃描到的藍牙設(shè)備信息,如:遠端設(shè)備地址、遠端設(shè)備名稱、遠端設(shè)備狀態(tài),并將其以日志的形式打印出來。在onStop()方法中取消藍牙設(shè)備掃描。打開遠程模擬器,打開藍牙,運行程序,界面顯示如圖所示。12.2.4案例:傳統(tǒng)藍牙的連接配對20單擊掃描按鈕,控制臺輸出內(nèi)容如下:06-0912:27:43.23822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:initBluetooth()方法被調(diào)用06-0912:27:43.25622192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:本機藍牙名稱為:HUAWEIP40,狀態(tài)為:2.06-0912:29:19.67022192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:B0:55:08:14:9D:7B,遠端設(shè)備名稱:HonorV12,遠端設(shè)備狀態(tài):0.06-0912:29:19.68322192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:20:AB:37:60:31:86,遠端設(shè)備名稱:“Administrator”的iPhone,遠端設(shè)備狀態(tài):0.06-0912:29:19.69222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:50:04:B8:C1:81:F8,遠端設(shè)備名稱:HISIP12PLUS,遠端設(shè)備狀態(tài):0.06-0912:29:19.69822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:1C:15:1F:8B:80:0E,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:19.70522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:50:04:B8:C1:82:CC,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:19.71522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:12:B1:F8:0E:B4:7D,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:19.72222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:0C:8F:FF:FD:49:34,遠端設(shè)備名稱:LOVERLIAN,遠端設(shè)備狀態(tài):0.12.2.4案例:傳統(tǒng)藍牙的連接配對21單擊配對按鈕,控制臺輸出內(nèi)容如下:06-0912:29:19.82522192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:30:74:96:55:F5:E3,遠端設(shè)備名稱:honorBand3-5e3,遠端設(shè)備狀態(tài):0.06-0912:29:21.66322192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:20:17:06:22:02:78,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:21.69222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:43:F1:F2:3B:3B:04,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:21.70222192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:40:96:54:76:07:BB,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:29:21.70822192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:遠端設(shè)備地址:40:96:54:76:07:BB,遠端設(shè)備名稱:,遠端設(shè)備狀態(tài):0.06-0912:30:03.18622192-22192/com.example.traditionalbluetoothdemoI00922/MainAbilitySlice:最終配對設(shè)備地址:40:96:54:76:07:BB,result:true.startPair()方法返回為ture,配對成功。010203040512.1藍牙開發(fā)概述12.2基于傳統(tǒng)藍牙開發(fā)12.3基于BLE低功耗藍牙開發(fā)12.4網(wǎng)絡(luò)管理開發(fā)概述12.5URL鏈接訪問CONTENTS12.3.1接口說明23BLE中心設(shè)備管理類BleCentralManager的主要接口,中心設(shè)備管理回調(diào)類BleCentralManagerCallback的主要接口,BLE廣播相關(guān)的BleAdvertiser類和BleAdvertiseCallback類的主要接口如下表所示。BLE中心設(shè)備管理類BleCentralManager的主要接口接口名功能描述startScan(List<BleScanFilter>filters)進行BLE藍牙掃描,并使用filters對結(jié)果進行過濾。stopScan()停止BLE藍牙掃描。getDevicesByStates(int[]states)停止BLE藍牙掃描。BleCentralManager(Contextcontext,BleCentralManagerCallbackcallback)獲取中心設(shè)備管理對象。12.3.1接口說明24中心設(shè)備管理回調(diào)類BleCentralManagerCallback的主要接口BLE廣播相關(guān)的BleAdvertiser類和BleAdvertiseCallback類的主要接口接口名功能描述scanResultEvent?(BleScanResultresult)掃描到BLE設(shè)備的結(jié)果回調(diào)。groupScanResultsEvent?(List<BleScanResult>scanResults)掃描到一組BLE設(shè)備的結(jié)果回調(diào)。scanFailedEvent?(intresultCode)啟動掃描失敗的回調(diào)。接口名功能描述BleAdvertiser(Contextcontext,BleAdvertiseCallbackcallback)用于獲取廣播操作對象。startAdvertising(BleAdvertiseSettingssettings,BleAdvertiseDataadvData,BleAdvertiseDatascanResponse)進行BLE廣播,第一個參數(shù)為廣播參數(shù),第二個為廣播數(shù)據(jù),第三個參數(shù)是掃描和廣播數(shù)據(jù)參數(shù)的響應(yīng)。stopAdvertising()停止BLE廣播。startResultEvent(intresult)廣播回調(diào)結(jié)果。12.3.2BLE掃描及廣播25中心設(shè)備進行BLE掃描操作流程如下:進行BLE掃描之前先要繼承BleCentralManagerCallback類實現(xiàn)scanResultEvent和scanFailedEvent回調(diào)函數(shù),用于接收掃描結(jié)果。調(diào)用BleCentralManager(BleCentralManagerCallbackcallback)接口獲取中心設(shè)備管理對象。獲取掃描過濾器,過濾器為空時為不使用過濾器掃描,然后調(diào)用startScan()開始掃描BLE設(shè)備,在回調(diào)中獲取掃描到的BLE設(shè)備。示例代碼如下://實現(xiàn)掃描回調(diào)publicclassScanCallbackimplementsBleCentralManagerCallback{List<BleScanResult>results=newArrayList<BleScanResult>();@OverridepublicvoidscanResultEvent(BleScanResultresultCode){//對掃描結(jié)果進行處理

results.add(resultCode);}12.3.2BLE掃描及廣播26獲取掃描過濾器,過濾器為空時為不使用過濾器掃描,然后調(diào)用startScan()開始掃描BLE設(shè)備,在回調(diào)中獲取掃描到的BLE設(shè)備。示例代碼如下:@OverridepublicvoidscanFailedEvent(intresultCode){HiLog.warn(TAG,"StartScanfailed,Code:%{public}d",resultCode);}@OverridepublicvoidgroupScanResultsEvent(finalList<BleScanResult>scanResults){//對掃描結(jié)果進行處理

}}//獲取中心設(shè)備管理對象privateScanCallbackcentralManagerCallback=newScanCallback();privateBleCentralManagercentralManager=newBleCentralManager(context,centralManagerCallback);//創(chuàng)建掃描過濾器然后開始掃描List<BleScanFilter>filters=newArrayList<BleScanFilter>();centralManager.startScan(filters);12.3.2BLE掃描及廣播27外圍設(shè)備進行BLE廣播操作流程如下:進行BLE廣播前需要先繼承advertiseCallback類實現(xiàn)startResultEvent回調(diào),用于獲取廣播結(jié)果。調(diào)用接口BleAdvertiser(Contextcontext,BleAdvertiseCallbackcallback)獲取廣播對象,構(gòu)造廣播參數(shù)和廣播數(shù)據(jù)。調(diào)用startAdvertising(BleAdvertiseSettingssettings,BleAdvertiseDataadvData,BleAdvertiseDatascanResponse)接口開始BLE廣播。示例代碼如下://實現(xiàn)BLE廣播回調(diào)privateBleAdvertiseCallbackadvertiseCallback=newBleAdvertiseCallback(){@OverridepublicvoidstartResultEvent(intresult){if(result==BleAdvertiseCallback.RESULT_SUCC){//開始BLE廣播成功

}else{//開始BLE廣播失敗

}}}12.3.2BLE掃描及廣播28//獲取BLE廣播對象privateBleAdvertiseradvertiser=newBleAdvertiser(this,advertiseCallback);//創(chuàng)建BLE廣播參數(shù)和數(shù)據(jù)privateBleAdvertiseDatadata=newBleAdvertiseData.Builder() //添加服務(wù)的UUID .addServiceUuid(SequenceUuid.uuidFromString(Server_UUID)) //添加廣播數(shù)據(jù)內(nèi)容 .addServiceData(SequenceUuid.uuidFromString(Server_UUID),newbyte[]{0x12}).build();privateBleAdvertiseSettingsadvertiseSettings=newBleAdvertiseSettings.Builder() //設(shè)置是否可連接廣播 .setConnectable(true) //設(shè)置廣播間隔 .setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT) //設(shè)置廣播功率 .setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT) .build();//開始廣播advertiser.startAdvertising(advertiseSettings,data,null);12.3.3案例:BLE藍牙的掃描與廣播29創(chuàng)建一個名為BleDemo的應(yīng)用來演示BLE藍牙中心設(shè)備掃描外圍設(shè)備和外圍設(shè)備向中心設(shè)備發(fā)出廣播。調(diào)用藍牙的打開接口及調(diào)用藍牙掃描接口需要申請權(quán)限,所以在config.json文件中請求權(quán)限內(nèi)容如下:"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其中權(quán)限ohos.permission.LOCATION為敏感權(quán)限,需要動態(tài)申請,在MainAbility文件中申請內(nèi)容如下:publicclassMainAbilityextendsAbility{@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setMainRoute(MainAbilitySlice.class.getName());if(verifySelfPermission("ohos.permission.LOCATION")!=IBundleManager.PERMISSION_GRANTED){//應(yīng)用未被授予權(quán)限if(canRequestPermission("ohos.permission.LOCATION")){//是否可以申請彈框授權(quán)(首次申請或者用戶未選擇禁止且不再提示)requestPermissionsFromUser(newString[]{"ohos.permission.LOCATION"},1);}else{//顯示應(yīng)用需要權(quán)限的理由,提示用戶進入設(shè)置授權(quán)}}else{//權(quán)限已被授予}}12.3.3案例:BLE藍牙的掃描與廣播31

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

//注意:因時間差導(dǎo)致接口權(quán)限檢查時有無權(quán)限

//所以對那些因無權(quán)限而拋異常的接口進行異常捕獲處理

}else{//權(quán)限被拒絕

}return;}}}12.3.3案例:BLE藍牙的掃描與廣播32修改MainAbilitySlice文件,其內(nèi)容如下:publicclassMainAbilitySliceextendsAbilitySlice{//定義日志標(biāo)簽privatestaticfinalHiLogLabelLABEL_LOG=newHiLogLabel(HiLog.LOG_APP,0x00922,"MainAbilitySlice");//獲取中心設(shè)備管理對象privateBleCentralManagerbleCentralManager;//獲取BLE廣播對象privateBleAdvertiserbleAdvertiser;//獲取BLE廣播數(shù)據(jù)對象privateBleAdvertiseDatableAdvertiseData;//獲取BLE廣播參數(shù)對象privateBleAdvertiseSettingsbleAdvertiseSettings;//隨機生成UUIDprivateUUIDServer_UUID=UUID.randomUUID();//連接狀態(tài)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()方法被調(diào)用");//獲取中心設(shè)備管理回調(diào)類對象ScanCallbackcentralManagerCallback=newScanCallback();//獲取中心設(shè)備管理對象bleCentralManager=newBleCentralManager(getContext(),centralManagerCallback);bleAdvertiser=newBleAdvertiser(this,advertiseCallback);

12.3.3案例:BLE藍牙的掃描與廣播34 //創(chuàng)建BLE廣播數(shù)據(jù)

bleAdvertiseData=newBleAdvertiseData.Builder()//添加服務(wù)的UUID.addServiceUuid(SequenceUuid.uuidFromString(String.valueOf(Server_UUID)))//添加廣播數(shù)據(jù)內(nèi)容

.addServiceData(SequenceUuid.uuidFromString(String.valueOf(Server_UUID)),newbyte[]{0x11}).build();//創(chuàng)建BLE廣播參數(shù)

bleAdvertiseSettings=newBleAdvertiseSettings.Builder()//設(shè)置是否可連接廣播

.setConnectable(true)//設(shè)置廣播間隔

.setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT)//設(shè)置廣播功率

.setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT).build();}12.3.3案例:BLE藍牙的掃描與廣播35 //初始化組件

privatevoidinitComponent(){ HiL(LABEL_LOG,"initComponent()方法被調(diào)用"); //找到組件

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,"開始掃描") //創(chuàng)建掃描過濾器開始掃描

List<BleScanFilter>filters=newArrayList<>(); //進行BLE藍牙掃描,并使用filters對結(jié)果進行過濾。

bleCentralManager.startScan(filters);

12.3.3案例:BLE藍牙的掃描與廣播36 //返回與指定狀態(tài)匹配的BlePeripheralDevice列表。

List<BlePeripheralDevice>devices=bleCentralManager.getDevicesByStaSTATES);for(BlePeripheralDevicedevice:devices){//獲取BLE外圍設(shè)備名

Optional<String>deviceNameOptional=device.getDeviceName();StringdeviceName=deviceNameOptional.orElse("");//獲取BLE外圍設(shè)備地址

StringdeviceAddr=device.getDeviceAddr();HiL(LABEL_LOG,"BLE外圍設(shè)備名:%{public}s"+",BLE外圍設(shè)備地址:%{public}s.",deviceName,deviceAddr);}}privatevoidAdvertise(Componentcomponent){HiL(LABEL_LOG,"開始廣播");//開始廣播

bleAdvertiser.startAdvertising(bleAdvertiseSettings,bleAdvertiseData,null);}12.3.3案例:BLE藍牙的掃描與廣播37 //實現(xiàn)掃描回調(diào)classScanCallbackimplementsBleCentralManagerCallback{List<BleScanResult>results=newArrayList<BleScanResult>();

@OverridepublicvoidscanResultEvent(BleScanResultresultCode){//對掃描結(jié)果進行處理results.add(resultCode);}

@OverridepublicvoidscanFailedEvent(intresultCode){

}

@OverridepublicvoidgroupScanResultsEvent(List<BleScanResult>list){

}}

12.3.3案例:BLE藍牙的掃描與廣播38 //實現(xiàn)BLE廣播回調(diào)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打開遠程模擬器,運行程序,應(yīng)用初始頁面如圖所示。單擊掃描按鈕,控制臺輸出內(nèi)容如下:06-0913:05:09.44417377-17377/com.example.bledemoI00922/MainAbilitySlice:initBluetooth()方法被調(diào)用06-0913:05:09.45217377-17377/com.example.bledemoI00922/MainAbilitySlice:initComponent()方法被調(diào)用06-0913:06:46.02817377-17377/com.example.bledemoI00922/MainAbilitySlice:開始掃描010203040512.1藍牙開發(fā)概述12.2基于傳統(tǒng)藍牙開發(fā)12.3基于BLE低功耗藍牙開發(fā)12.4網(wǎng)絡(luò)管理開發(fā)概述12.5URL鏈接訪問CONTENTS12.4網(wǎng)絡(luò)管理開發(fā)概述41HarmonyOS網(wǎng)絡(luò)管理模塊主要提供以下功能:數(shù)據(jù)連接管理:網(wǎng)卡綁定,打開URL,數(shù)據(jù)鏈路參數(shù)查詢。數(shù)據(jù)網(wǎng)絡(luò)管理:指定數(shù)據(jù)網(wǎng)絡(luò)傳輸,獲取數(shù)據(jù)網(wǎng)絡(luò)狀態(tài)變更,數(shù)據(jù)網(wǎng)絡(luò)狀態(tài)查詢。使用網(wǎng)絡(luò)管理模塊的相關(guān)功能時,需要請求相應(yīng)的權(quán)限。如下表所示:權(quán)限名權(quán)限描述ohos.permission.GET_NETWORK_INFO獲取網(wǎng)絡(luò)連接信息。ohos.permission.SET_NETWORK_INFO修改網(wǎng)絡(luò)連接狀態(tài)。ohos.permission.INTERNET允許程序打開網(wǎng)絡(luò)套接字,進行網(wǎng)絡(luò)連接。010203040512.1藍牙開發(fā)概述12.2基于傳統(tǒng)藍牙開發(fā)12.3基于BLE低功耗藍牙開發(fā)12.4網(wǎng)絡(luò)管理開發(fā)概述12.5URL鏈接訪問CONTENTS12.5.1接口說明43URL鏈接訪問,所使用的接口如下表所示類名接口名功能描述NetManagergetInstance(Contextcontext)獲取網(wǎng)絡(luò)管理的實例對象。hasDefaultNet()查詢當(dāng)前是否有默認(rèn)可用的數(shù)據(jù)網(wǎng)絡(luò)。getDefaultNet()獲取當(dāng)前默認(rèn)的數(shù)據(jù)網(wǎng)絡(luò)句柄。addDefaultNetStatusCallback(NetStatusCallbackcallback)獲取當(dāng)前默認(rèn)的數(shù)據(jù)網(wǎng)絡(luò)狀態(tài)變化。setAppNet(NetHandlenetHandle)應(yīng)用綁定該數(shù)據(jù)網(wǎng)絡(luò)。NetHandleopenConnection(URLurl,.Proxyproxy)throwsIOException使用該網(wǎng)絡(luò)打開一個URL鏈接。12.5.2開發(fā)步驟44調(diào)用NetManager.getInstance(Context)獲取網(wǎng)絡(luò)管理的實例對象。調(diào)用NetManager.getDefaultNet()獲取默認(rèn)的數(shù)據(jù)網(wǎng)絡(luò)。調(diào)用NetHandle.openConnection()打開一個URL。通過URL鏈接實例訪問網(wǎng)站。示例代碼如下:NetManagernetManager=NetManager.getInstance(context);if(!netManager.hasDefaultNet()){return;}NetHandlenetHandle=netManager.getDefaultNet();//可以獲取網(wǎng)絡(luò)狀態(tài)的變化NetStatusCallbackcallback=newNetStatusCallback(){//重寫需要獲取的網(wǎng)絡(luò)狀態(tài)變化的override函數(shù)};netManager.addDefaultNetStatusCallback(callback);12.5.2開發(fā)步驟45//通過openConnection來獲取URLConnectionHttpURLConnectionconnection=null;try{StringurlString="EXAMPLE_URL";//開發(fā)者根據(jù)實際情況自定義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創(chuàng)建一個名為URLAccessDemo的應(yīng)用來演示在手機中打開一個URL鏈接并將鏈接中的文本信息渲染在屏幕上。"deviceConfig":{"default":{"directLaunch":false,"network":{"cleartextTraffic":true}}}使用網(wǎng)絡(luò)管理模塊的相關(guān)功能時,需要請求相應(yīng)的權(quán)限,且由于HarmonyOS默認(rèn)支持HTTPS協(xié)議,若要使用HTTP協(xié)議,需要在config.json中進行配置。使用HTTP協(xié)議需進行如下配置:12.5.3案例:URL鏈接訪問47"reqPermissions":[{ "name":"ohos.permission.GET_NETWORK_INFO"},{ "name":"ohos.permission.SET_NETWORK_INFO"},{ "name":"ohos.permission.INTERNET"}]使用網(wǎng)絡(luò)管理模塊的相關(guān)功能需要請求如下權(quán)限:12.5.3案例:URL鏈接訪問48創(chuàng)建一個名為HttpRequestUtil的工具類,用戶只需要提供URL即可完成請求工作,修改其容如下:publicclassHttpRequestUtil{privatestaticStringsendRequest(Contextcontext,StringurlString,Stringmethod,Stringtoken,Stringdata){//返回結(jié)果Stringresult=null;//獲取網(wǎng)絡(luò)管理的實例對象NetManagernetManager=NetManager.getInstance(context);//如果默認(rèn)數(shù)據(jù)網(wǎng)絡(luò)沒有被激活,則返回if(!netManager.hasDefaultNet()){returnnull;}//獲取默認(rèn)的數(shù)據(jù)網(wǎng)絡(luò)NetHandlenetHandle=netManager.getDefaultNet();//可以獲取網(wǎng)絡(luò)狀態(tài)的變化NetStatusCallbackcallback=newNetStatusCallback(){//重寫需要獲取的網(wǎng)絡(luò)狀態(tài)變化的override函數(shù)};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;//設(shè)置請求方式,這里為GETconnection.setRequestMethod(method);//如果通過請求體傳遞參數(shù)到服務(wù)端接口,需要對connection進行額外的設(shè)置if(data!=null){//允許通過此網(wǎng)絡(luò)連接向服務(wù)端寫數(shù)據(jù)connection.setDoOutput(true);//設(shè)置請求頭connection.setRequestProperty("Content-Type","application/json;Charset=utf-8");}12.5.3案例:URL鏈接訪問50 //如果參數(shù)token!=null,則需要將token設(shè)置到請求頭if(token!=null){connection.setRequestProperty("token",token);}//發(fā)送請求建立連接connection.connect();

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論