自己可以做企业网站吗wordpress 4 xmlrpc
自己可以做企业网站吗,wordpress 4 xmlrpc,wordpress阿里百秀模板下载,dede wap网站模板下载一、什么是星闪#xff1f;
星闪#xff08;NearLink#xff09; 是华为研发的新一代短距离无线通信技术#xff0c;可以理解为华为版蓝牙#xff08;仅限我们目前用的#xff0c;有对标WiFi的版本#xff09;#xff0c;但比蓝牙更快、更稳、更省电。
星…一、什么是星闪星闪NearLink是华为研发的新一代短距离无线通信技术可以理解为华为版蓝牙仅限我们目前用的有对标WiFi的版本但比蓝牙更快、更稳、更省电。星闪的优点低延迟、高带宽、低功耗。星闪的缺点当前只能连接华为设备不能连 iPhone 等其他设备设备还不多在发展中开发星闪应用需要什么一台华为手机运行 HarmonyOS 5.0星闪支持较好一个星闪设备或另一台华为手机DevEco Studio 开发工具二、第一步导入需要的模块// common/NearLinkManager.ets // 这个文件放在 entry/src/main/ets/common/ 目录下// 星闪功能模块import{scan,advertising,ssap,constant}fromkit.NearLinkKit;// scan: 扫描设备// advertising: 发送广播可选// ssap: 星闪应用层协议类似蓝牙的 GATT// constant: 常量定义// 权限管理模块import{abilityAccessCtrl,Permissions,common}fromkit.AbilityKit;// 错误处理模块import{BusinessError}fromkit.BasicServicesKit;// 日志模块可选import{hilog}fromkit.PerformanceAnalysisKit;三、第二步配置权限星闪只需要一个权限比蓝牙简单多了3.1 静态权限声明// entry/src/main/module.json5 // 只需要这一个权限是不是超简单{module:{requestPermissions:[{name:ohos.permission.ACCESS_NEARLINK,// 星闪权限就这一个reason:$string:nearlink_permission_reason,usedScene:{abilities:[EntryAbility],when:inuse}}]}}3.2 权限说明字符串// entry/src/main/resources/base/element/string.json {string:[{name:nearlink_permission_reason,value:需要星闪权限以连接和控制星闪设备}]}3.3 动态权限申请弹窗让用户确认// common/PermissionManager.ets import{abilityAccessCtrl,Permissions,common}fromkit.AbilityKit;exportclassPermissionManager{privatestaticinstance:PermissionManager;privatecontext?:common.UIAbilityContext;publicstaticgetInstance():PermissionManager{if(!PermissionManager.instance){PermissionManager.instancenewPermissionManager();}returnPermissionManager.instance;}publicsetContext(context:common.UIAbilityContext):void{this.contextcontext;}/** * 检查并申请星闪权限 * returns 是否已授权 */publicasynccheckAndRequestNearLinkPermissions():Promiseboolean{if(!this.context){console.error(Context not set);returnfalse;}constpermission:Permissionsohos.permission.ACCESS_NEARLINK;try{constatManagerabilityAccessCtrl.createAtManager();// 检查权限constgrantStatusawaitatManager.checkAccessToken(this.context.applicationInfo.accessTokenId,permission);if(grantStatus!abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED){// 权限未授予请求用户授权constrequestResultawaitatManager.requestPermissionsFromUser(this.context,[permission]);if(requestResult.authResults[0]!abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED){console.error(NearLink permission denied by user);returnfalse;}}console.info(NearLink permission granted);returntrue;}catch(error){console.error(Permission request failed:${error});returnfalse;}}}3.4 在 EntryAbility 中初始化应用启动时设置// EntryAbility.ets import{AbilityConstant,UIAbility,Want}fromkit.AbilityKit;import{window}fromkit.ArkUI;import{PermissionManager}from../common/PermissionManager;import{NearLinkManager}from../common/NearLinkManager;exportdefaultclassEntryAbilityextendsUIAbility{onCreate(want:Want,launchParam:AbilityConstant.LaunchParam):void{console.info(EntryAbility onCreate);}onWindowStageCreate(windowStage:window.WindowStage):void{// 设置上下文PermissionManager.getInstance().setContext(this.context);NearLinkManager.getInstance().setContext(this.context);windowStage.loadContent(pages/Index,(err){if(err.code){console.error(Failed to load content);return;}});}}四、第三步SSAP 客户端实现核心代码SSAP 是什么星闪应用层协议StarShine Application Protocol类似蓝牙的 GATT用来定义数据如何传输。术语对照蓝牙星闪说明GATTSSAP应用层协议CharacteristicProperty数据容器ServiceService服务分组4.1 SSAP 客户端管理器// common/SSAPClient.ets // 这个文件放在 entry/src/main/ets/common/ 目录下import{ssap,constant}fromkit.NearLinkKit;import{BusinessError}fromkit.BasicServicesKit;// 数据类型定义 // 连接状态枚举exportenumConnectionState{DISCONNECTED0,// 已断开CONNECTING1,// 连接中...CONNECTED2,// 已连接DISCONNECTING3// 断开中...}// 属性权限枚举这个属性能读/能写/能通知exportenumPropertyPermission{READ0x01,// 可读WRITE0x02,// 可写NOTIFY0x04// 可接收通知}// 连接状态变化信息exportinterfaceConnectionChangeState{address:string;state:ConnectionState;}// 属性通知信息exportinterfacePropertyNotification{address:string;serviceId:string;propertyId:string;value:ArrayBuffer;}// 发现的服务exportinterfaceDiscoveredService{serviceId:string;properties:DiscoveredProperty[];}// 发现的属性exportinterfaceDiscoveredProperty{propertyId:string;permissions:PropertyPermission[];}// 客户端信息interfaceClientInfo{address:string;client:ssap.Client;services:Arrayssap.Service;connectionState:ConnectionState;}exportclassSSAPClient{privatestaticinstance:SSAPClient;privateclientMap:Mapstring,ClientInfonewMap();// 回调函数privateconnectionStateCallbacks:((state:ConnectionChangeState)void)[][];privatepropertyNotificationCallbacks:((notification:PropertyNotification)void)[][];privateconstructor(){}publicstaticgetInstance():SSAPClient{if(!SSAPClient.instance){SSAPClient.instancenewSSAPClient();}returnSSAPClient.instance;}/** * 连接到 SSAP 服务端连接星闪设备 * param address 设备地址 * returns 是否连接成功 */publicasyncconnectToServer(address:string):Promiseboolean{try{// 检查是否已连接防止重复连接if(this.clientMap.has(address)){constexistingthis.clientMap.get(address);if(existing?.connectionStateConnectionState.CONNECTED){console.info(已经连接了这个设备:${address});returntrue;}}console.info(正在连接星闪设备:${address});// 创建 SSAP 客户端constclient:ssap.Clientssap.createClient(address);constclientInfo:ClientInfo{address:address,client:client,services:[],connectionState:ConnectionState.CONNECTING};this.clientMap.set(address,clientInfo);// 注册连接状态变化回调client.on(connectionStateChange,(data:ssap.ConnectionChangeState){this.handleConnectionStateChange(address,data);});// 注册属性变化回调client.on(propertyChange,(data:ssap.Property){this.handlePropertyChange(address,data);});// 连接awaitclient.connect();console.info(Connection request sent:${address});returntrue;}catch(error){console.error(Connect failed:${error});this.clientMap.delete(address);returnfalse;}}/** * 处理连接状态变化 */privatehandleConnectionStateChange(address:string,data:ssap.ConnectionChangeState):void{constclientInfothis.clientMap.get(address);if(!clientInfo)return;letnewState:ConnectionState;if(data.stateconstant.ConnectionState.STATE_CONNECTED){newStateConnectionState.CONNECTED;clientInfo.connectionStatenewState;// 连接成功后获取服务列表this.getServices(address);}elseif(data.stateconstant.ConnectionState.STATE_DISCONNECTED){newStateConnectionState.DISCONNECTED;clientInfo.connectionStatenewState;clientInfo.services[];}elseif(data.stateconstant.ConnectionState.STATE_CONNECTING){newStateConnectionState.CONNECTING;clientInfo.connectionStatenewState;}elseif(data.stateconstant.ConnectionState.STATE_DISCONNECTING){newStateConnectionState.DISCONNECTING;clientInfo.connectionStatenewState;}else{newStateConnectionState.DISCONNECTED;}// 通知所有订阅者constchangeState:ConnectionChangeState{address,state:newState};this.connectionStateCallbacks.forEach(callbackcallback(changeState));}/** * 处理属性变化 */privatehandlePropertyChange(address:string,data:ssap.Property):void{constnotification:PropertyNotification{address:address,serviceId:data.serviceUuid,propertyId:data.propertyUuid,value:data.value};this.propertyNotificationCallbacks.forEach(callbackcallback(notification));}/** * 获取服务列表 */privateasyncgetServices(address:string):Promisevoid{try{constclientInfothis.clientMap.get(address);if(!clientInfo)return;constservices:Arrayssap.ServiceawaitclientInfo.client.getServices();clientInfo.servicesservices;console.info(Discovered${services.length}services);// 自动设置属性通知for(constserviceofservices){for(constpropofservice.properties){awaitthis.subscribePropertyNotification(address,service.serviceUuid,prop.propertyUuid);}}}catch(error){console.error(Get services failed:${error});}}/** * 读取属性值 */publicasyncreadProperty(address:string,serviceId:string,propertyId:string):PromiseArrayBuffer|null{try{constclientInfothis.clientMap.get(address);if(!clientInfo||clientInfo.services.length0){console.error(Client not found or services not discovered);returnnull;}constproperty:ssap.Property{serviceUuid:serviceId,propertyUuid:propertyId,value:newArrayBuffer(1)};constresult:ssap.PropertyawaitclientInfo.client.readProperty(property);returnresult.value;}catch(error){console.error(Read property failed:${error});returnnull;}}/** * 写入属性值双重写入策略 */publicasyncwriteProperty(address:string,serviceId:string,propertyId:string,value:ArrayBuffer):Promiseboolean{try{constclientInfothis.clientMap.get(address);if(!clientInfo||clientInfo.services.length0){console.error(Client not found or services not discovered);returnfalse;}constproperty:ssap.Property{serviceUuid:serviceId,propertyUuid:propertyId,value:value};// 双重写入策略try{awaitclientInfo.client.writeProperty(property,ssap.PropertyWriteType.WRITE);console.info(Write property success (WRITE mode));returntrue;}catch(writeError){console.warn(WRITE mode failed, trying WRITE_NO_RESPONSE);awaitclientInfo.client.writeProperty(property,ssap.PropertyWriteType.WRITE_NO_RESPONSE);console.info(Write property success (WRITE_NO_RESPONSE mode));returntrue;}}catch(error){console.error(Write property failed:${error});returnfalse;}}/** * 订阅属性通知 */publicasyncsubscribePropertyNotification(address:string,serviceId:string,propertyId:string):Promiseboolean{try{constclientInfothis.clientMap.get(address);if(!clientInfo)returnfalse;constproperty:ssap.Property{serviceUuid:serviceId,propertyUuid:propertyId,value:newArrayBuffer(1)};awaitclientInfo.client.setPropertyNotification(property,true);returntrue;}catch(error){console.error(Subscribe notification failed:${error});returnfalse;}}/** * 断开连接 */publicasyncdisconnectFromServer(address:string):Promisevoid{try{constclientInfothis.clientMap.get(address);if(!clientInfo)return;awaitclientInfo.client.disconnect();clientInfo.client.off(propertyChange);clientInfo.client.off(connectionStateChange);clientInfo.client.close();this.clientMap.delete(address);console.info(Disconnected from:${address});}catch(error){console.error(Disconnect failed:${error});}}/** * 获取发现的服务 */publicgetDiscoveredServices(address:string):DiscoveredService[]{constclientInfothis.clientMap.get(address);if(!clientInfo)return[];returnclientInfo.services.map((service:ssap.Service):DiscoveredService({serviceId:service.serviceUuid,properties:service.properties.map((prop:ssap.Property):DiscoveredProperty({propertyId:prop.propertyUuid,permissions:[PropertyPermission.READ,PropertyPermission.WRITE,PropertyPermission.NOTIFY]}))}));}// 回调管理publiconConnectionStateChange(callback:(state:ConnectionChangeState)void):void{this.connectionStateCallbacks.push(callback);}publiconPropertyNotification(callback:(notification:PropertyNotification)void):void{this.propertyNotificationCallbacks.push(callback);}}四、第三步星闪管理器核心代码这是整个星闪功能的核心包含扫描、连接、收发数据等所有功能。// common/NearLinkManager.ets import{scan,advertising}fromkit.NearLinkKit;import{common}fromkit.AbilityKit;import{BusinessError}fromkit.BasicServicesKit;import{SSAPClient,ConnectionState,DiscoveredService,ConnectionChangeState,PropertyNotification}from./SSAPClient;// 扫描结果接口exportinterfaceScanResult{deviceId:string;deviceName:string;address:string;rssi:number;}// 扫描过滤器接口exportinterfaceScanFilter{deviceName?:string;address?:string;}exportclassNearLinkManager{privatestaticinstance:NearLinkManager;privatecontext?:common.UIAbilityContext;privateisScanning:booleanfalse;privatescanResults:Mapstring,ScanResultnewMap();privateconnectedDevice?:ScanResult;// 回调函数privateonDeviceFoundCallback?:(device:ScanResult)void;privateconnectionStateCallbacks:((device:ScanResult,state:ConnectionState)void)[][];privateonDataReceivedCallback?:(data:ArrayBuffer)void;// SSAP客户端privatessapClient:SSAPClientSSAPClient.getInstance();privateconstructor(){this.setupSSAPClientCallback();}publicstaticgetInstance():NearLinkManager{if(!NearLinkManager.instance){NearLinkManager.instancenewNearLinkManager();}returnNearLinkManager.instance;}publicsetContext(context:common.UIAbilityContext):void{this.contextcontext;}/** * 设置 SSAP 客户端回调 */privatesetupSSAPClientCallback():void{// 连接状态变化回调this.ssapClient.onConnectionStateChange((state:ConnectionChangeState){if(this.connectedDevicethis.connectionStateCallbacks.length0){letconnectionState:ConnectionState;switch(state.state){case0:connectionStateConnectionState.DISCONNECTED;break;case1:connectionStateConnectionState.CONNECTING;break;case2:connectionStateConnectionState.CONNECTED;break;case3:connectionStateConnectionState.DISCONNECTING;break;default:connectionStateConnectionState.DISCONNECTED;}this.connectionStateCallbacks.forEach(callback{callback(this.connectedDevice!,connectionState);});}});// 属性通知回调this.ssapClient.onPropertyNotification((notification:PropertyNotification){if(this.onDataReceivedCallback){this.onDataReceivedCallback(notification.value);}});}/** * 开始扫描 */publicstartScan(filters?:ScanFilter[]):void{if(this.isScanning){console.warn(Already scanning);return;}try{this.isScanningtrue;this.scanResults.clear();// 注册设备发现回调scan.on(deviceFound,(data:Arrayscan.ScanResults){data.forEach((result:scan.ScanResults){constdevice:ScanResult{deviceId:result.address,deviceName:result.deviceName||未知设备,address:result.address,rssi:result.rssi||-100};// 去重if(!this.scanResults.has(device.address)){this.scanResults.set(device.address,device);if(this.onDeviceFoundCallback){this.onDeviceFoundCallback(device);}}});});// 配置扫描参数constscanOptions:scan.ScanOptions{scanMode:2// 平衡扫描模式};// 构建过滤器constscanFilters:scan.ScanFilters[][];if(filtersfilters.length0){filters.forEach(filter{constnearLinkFilter:scan.ScanFilters{};if(filter.deviceName){nearLinkFilter.deviceNamefilter.deviceName;}if(filter.address){nearLinkFilter.addressfilter.address;}scanFilters.push(nearLinkFilter);});}constfiltersToUsescanFilters.length0?scanFilters:[({}asscan.ScanFilters)];scan.startScan(filtersToUse,scanOptions).then((){console.info(NearLink scan started);}).catch((err:BusinessError){console.error(Start scan failed:${err.message});this.isScanningfalse;});}catch(error){console.error(Start scan exception:${error});this.isScanningfalse;}}/** * 停止扫描 */publicstopScan():void{if(!this.isScanning)return;try{scan.stopScan().then(()console.info(NearLink scan stopped)).catch((err:BusinessError)console.error(Stop scan failed:${err.message}));scan.off(deviceFound);this.isScanningfalse;}catch(error){console.error(Stop scan exception:${error});}}/** * 连接设备 */publicasyncconnectDevice(device:ScanResult):Promiseboolean{try{this.connectedDevicedevice;constsuccessawaitthis.ssapClient.connectToServer(device.address);returnsuccess;}catch(error){console.error(Connect device failed:${error});this.connectedDeviceundefined;returnfalse;}}/** * 断开连接 */publicasyncdisconnectDevice():Promisevoid{if(!this.connectedDevice)return;try{awaitthis.ssapClient.disconnectFromServer(this.connectedDevice.address);this.connectedDeviceundefined;}catch(error){console.error(Disconnect failed:${error});}}/** * 发送数据 */publicasyncsendData(serviceId:string,propertyId:string,data:ArrayBuffer):Promiseboolean{if(!this.connectedDevice)returnfalse;returnawaitthis.ssapClient.writeProperty(this.connectedDevice.address,serviceId,propertyId,data);}// 回调设置publicsetOnDeviceFoundCallback(callback:(device:ScanResult)void):void{this.onDeviceFoundCallbackcallback;}publicsetOnConnectionStateChangedCallback(callback:(device:ScanResult,state:ConnectionState)void):void{if(!this.connectionStateCallbacks.includes(callback)){this.connectionStateCallbacks.push(callback);}}publicsetOnDataReceivedCallback(callback:(data:ArrayBuffer)void):void{this.onDataReceivedCallbackcallback;}// GetterpublicgetIsScanning():boolean{returnthis.isScanning;}publicgetConnectedDevice():ScanResult|undefined{returnthis.connectedDevice;}publicgetDiscoveredServices():DiscoveredService[]{if(!this.connectedDevice)return[];returnthis.ssapClient.getDiscoveredServices(this.connectedDevice.address);}}六、UI 组件实现6.1 设备卡片组件// pages/NearLinkConnectionPage.ets import{ScanResult,ConnectionState}from../common/NearLinkManager;Component struct NearLinkDeviceCard{Prop device:ScanResult;Prop isConnected:booleanfalse;onConnect?:()void;privategetSignalColor(rssi:number):string{if(rssi-50)return#4CAF50;if(rssi-70)return#FF9800;return#FF5722;}build(){Row(){// 左侧设备信息Column(){Row(){Text(this.device.deviceName).fontSize(16).fontWeight(FontWeight.Medium).fontColor(this.isConnected?#9C27B0:#333333).layoutWeight(1)// 星闪标识Text(NearLink).fontSize(10).fontColor(#9C27B0).backgroundColor(rgba(156, 39, 176, 0.1)).padding({left:6,right:6,top:2,bottom:2}).borderRadius(4)}.width(100%)Row(){Text(this.device.address).fontSize(12).fontColor(#999999).layoutWeight(1)Text(${this.device.rssi}dBm).fontSize(12).fontColor(this.getSignalColor(this.device.rssi))}.width(100%).margin({top:4})}.layoutWeight(1).alignItems(HorizontalAlign.Start)// 连接按钮Button(this.isConnected?断开:连接).fontSize(14).backgroundColor(this.isConnected?#FF5722:#9C27B0).fontColor(Color.White).height(36).width(70).margin({left:12}).onClick((){if(this.onConnect){this.onConnect();}})}.width(100%).padding(16).backgroundColor(Color.White).borderRadius(12).shadow({radius:4,color:rgba(0,0,0,0.1),offsetY:2})}}6.2 设备列表页面// pages/NearLinkConnectionPage.ets import{NearLinkManager,ScanResult,ConnectionState}from../common/NearLinkManager;import{PermissionManager}from../common/PermissionManager;import{promptAction}fromkit.ArkUI;Entry Component struct NearLinkConnectionPage{State discoveredDevices:ScanResult[][];State isScanning:booleanfalse;State connectedDevice:ScanResult|nullnull;privatenearLinkManager:NearLinkManagerNearLinkManager.getInstance();aboutToAppear():void{// 设置设备发现回调this.nearLinkManager.setOnDeviceFoundCallback((device:ScanResult){constexiststhis.discoveredDevices.find(dd.addressdevice.address);if(!exists){this.discoveredDevices[...this.discoveredDevices,device];}});// 设置连接状态回调this.nearLinkManager.setOnConnectionStateChangedCallback((device:ScanResult,state:ConnectionState){if(stateConnectionState.CONNECTED){this.connectedDevicedevice;promptAction.showToast({message:已连接:${device.deviceName}});}elseif(stateConnectionState.DISCONNECTED){this.connectedDevicenull;promptAction.showToast({message:设备已断开});}});}aboutToDisappear():void{this.nearLinkManager.stopScan();}privateasyncstartScan():Promisevoid{// 检查并申请权限consthasPermissionawaitPermissionManager.getInstance().checkAndRequestNearLinkPermissions();if(!hasPermission){promptAction.showToast({message:请授予星闪权限后重试});return;}this.discoveredDevices[];this.nearLinkManager.startScan();this.isScanningtrue;// 10秒后自动停止扫描setTimeout((){this.stopScan();},10000);}privatestopScan():void{this.nearLinkManager.stopScan();this.isScanningfalse;}privateasynconDeviceClick(device:ScanResult):Promisevoid{if(this.connectedDevice?.addressdevice.address){awaitthis.nearLinkManager.disconnectDevice();}else{this.stopScan();awaitthis.nearLinkManager.connectDevice(device);}}build(){Column(){// 标题栏Row(){Text(星闪设备).fontSize(20).fontWeight(FontWeight.Bold)Blank()Button(this.isScanning?停止扫描:开始扫描).fontSize(14).backgroundColor(this.isScanning?#FF5722:#9C27B0).onClick((){if(this.isScanning){this.stopScan();}else{this.startScan();}})}.width(100%).padding(16)// 扫描状态if(this.isScanning){Row(){LoadingProgress().width(20).height(20).color(#9C27B0)Text(正在扫描星闪设备...).fontSize(14).fontColor(#666666).margin({left:8})}.width(100%).justifyContent(FlexAlign.Center).padding(16)}// 设备列表if(this.discoveredDevices.length0){Column(){Text(⚡).fontSize(48).margin({bottom:16})Text(this.isScanning?正在搜索星闪设备...:未发现设备).fontSize(16).fontColor(#999999)}.width(100%).height(200).justifyContent(FlexAlign.Center)}else{List({space:12}){ForEach(this.discoveredDevices,(device:ScanResult){ListItem(){NearLinkDeviceCard({device:device,isConnected:this.connectedDevice?.addressdevice.address,onConnect:()this.onDeviceClick(device)})}},(device:ScanResult)device.address)}.width(100%).layoutWeight(1).padding({left:16,right:16})}}.width(100%).height(100%).backgroundColor(#F5F5F5)}}6.3 服务/属性卡片组件// pages/NearLinkDeviceDetailPage.ets import{NearLinkManager,DiscoveredService,DiscoveredProperty}from../common/NearLinkManager;import{router}fromkit.ArkUI;Entry Component struct NearLinkDeviceDetailPage{State services:DiscoveredService[][];privatenearLinkManager:NearLinkManagerNearLinkManager.getInstance();aboutToAppear():void{this.servicesthis.nearLinkManager.getDiscoveredServices();}privateimportUUID(serviceId:string,propertyId:string):void{router.pushUrl({url:pages/SettingsPage,params:{importServiceUUID:serviceId,importCharacteristicUUID:propertyId}});}BuilderServiceCard(service:DiscoveredService,index:number){Column(){// 服务标题Row(){Text(服务${index1}).fontSize(14).fontWeight(FontWeight.Medium).fontColor(#333333)Blank()Text(SSAP Service).fontSize(12).fontColor(#9C27B0).backgroundColor(rgba(156, 39, 176, 0.1)).padding({left:8,right:8,top:2,bottom:2}).borderRadius(4)}.width(100%).margin({bottom:8})// 服务 UUIDText(service.serviceId).fontSize(12).fontColor(#666666).width(100%).margin({bottom:12})// 属性列表if(service.properties.length0){Text(属性列表).fontSize(13).fontColor(#999999).width(100%).margin({bottom:8})ForEach(service.properties,(prop:DiscoveredProperty,propIndex:number){Row(){Column(){Text(属性${propIndex1}).fontSize(12).fontColor(#333333)Text(prop.propertyId).fontSize(11).fontColor(#999999).maxLines(1).textOverflow({overflow:TextOverflow.Ellipsis})}.layoutWeight(1).alignItems(HorizontalAlign.Start)Button(导入).fontSize(12).height(28).backgroundColor(#9C27B0).fontColor(Color.White).onClick((){this.importUUID(service.serviceId,prop.propertyId);})}.width(100%).padding(8).backgroundColor(#F5F5F5).borderRadius(4).margin({bottom:4})},(prop:DiscoveredProperty)prop.propertyId)}}.width(100%).padding(16).backgroundColor(Color.White).borderRadius(12).shadow({radius:2,color:rgba(0,0,0,0.1),offsetY:1})}build(){Column(){// 标题栏Row(){Button(返回).backgroundColor(Color.Transparent).fontColor(#9C27B0).onClick(()router.back())Text(设备详情).fontSize(18).fontWeight(FontWeight.Medium).layoutWeight(1).textAlign(TextAlign.Center)Text().width(60)}.width(100%).padding(16)// 服务列表if(this.services.length0){Column(){Text(未发现服务).fontSize(16).fontColor(#999999)}.width(100%).height(200).justifyContent(FlexAlign.Center)}else{Scroll(){Column({space:12}){ForEach(this.services,(service:DiscoveredService,index:number){this.ServiceCard(service,index)},(service:DiscoveredService)service.serviceId)}.width(100%).padding(16)}.layoutWeight(1)}}.width(100%).height(100%).backgroundColor(#F5F5F5)}}6.4 UUID 配置页面// pages/NearLinkSettingsPage.ets import{router}fromkit.ArkUI;Entry Component struct NearLinkSettingsPage{State serviceUUID:string;State propertyUUID:string;State filterEnabled:booleanfalse;State filterDeviceName:string;aboutToAppear():void{constparamsrouter.getParams()asRecordstring,string;if(params){if(params.importServiceUUID){this.serviceUUIDparams.importServiceUUID;}if(params.importCharacteristicUUID){this.propertyUUIDparams.importCharacteristicUUID;}}}BuilderUUIDConfigSection(){Column(){Text(UUID 配置).fontSize(16).fontWeight(FontWeight.Medium).alignSelf(ItemAlign.Start).margin({bottom:16})// 服务 UUIDRow(){Text(服务UUID).fontSize(14).fontColor(#666666).width(80)TextInput({placeholder:请输入服务UUID,text:this.serviceUUID}).layoutWeight(1).margin({left:12,right:12}).onChange((value:string){this.serviceUUIDvalue;})Button(重置).fontSize(12).backgroundColor(#F5F5F5).fontColor(#9C27B0).width(60).height(32).onClick((){this.serviceUUID;})}.width(100%).margin({bottom:12})// 属性 UUIDRow(){Text(属性UUID).fontSize(14).fontColor(#666666).width(80)TextInput({placeholder:请输入属性UUID,text:this.propertyUUID}).layoutWeight(1).margin({left:12,right:12}).onChange((value:string){this.propertyUUIDvalue;})Button(重置).fontSize(12).backgroundColor(#F5F5F5).fontColor(#9C27B0).width(60).height(32).onClick((){this.propertyUUID;})}.width(100%).margin({bottom:8})Text(UUID格式37bea880-fc70-11ea-b720-00000000fdee).fontSize(12).fontColor(#999999).alignSelf(ItemAlign.Start)}.width(100%).padding(16).backgroundColor(Color.White).borderRadius(12)}build(){Column(){// 标题栏Row(){Button(返回).backgroundColor(Color.Transparent).fontColor(#9C27B0).onClick(()router.back())Text(星闪设置).fontSize(18).fontWeight(FontWeight.Medium).layoutWeight(1).textAlign(TextAlign.Center)Button(保存).backgroundColor(Color.Transparent).fontColor(#9C27B0).onClick(()router.back())}.width(100%).padding(16)Scroll(){Column({space:16}){this.UUIDConfigSection()}.width(100%).padding(16)}.layoutWeight(1)}.width(100%).height(100%).backgroundColor(#F5F5F5)}}七、广播发送高级用法可选什么是广播让你的手机也能被其他星闪设备发现类似于使你的手机变成一个星闪设备。什么时候用当你需要手机对手机通信或者你在开发服务端功能时。// common/NearLinkManager.ets补充/** * 开始广播 */publicstartAdvertising():void{try{constsetting:advertising.AdvertisingSettings{interval:160,power:2};constmanufactureData:advertising.ManufacturerData{manufacturerId:4567,manufacturerData:newUint8Array([1,2,3,4]).buffer};constserviceData:advertising.ServiceData{serviceUuid:37bea880-fc70-11ea-b720-00000000fdee,serviceData:newUint8Array([5,6,7,8]).buffer};constadvData:advertising.AdvertisingData{serviceUuids:[37bea880-fc70-11ea-b720-00000000fdee],manufacturerData:[manufactureData],serviceData:[serviceData],includeDeviceName:true};constadvertisingParams:advertising.AdvertisingParams{advertisingSettings:setting,advertisingData:advData};advertising.startAdvertising(advertisingParams).then((handle:number){console.info(Advertising started, handle:${handle});}).catch((err){console.error(Start advertising failed:${err.message});});}catch(error){console.error(Start advertising exception:${error});}}/** * 停止广播 */publicstopAdvertising(handle:number):void{try{advertising.stopAdvertising(handle).then(()console.info(Advertising stopped)).catch((err)console.error(Stop advertising failed:${err.message}));}catch(error){console.error(Stop advertising exception:${error});}}八、最佳实践踩坑总结8.1 必须遵守的规则权限先行扫描前必须检查并申请权限只要1个资源释放页面销毁时停止扫描、断开连接状态同步使用回调机制同步 UI 状态多设备管理使用 Map 管理多个连接8.2 常见问题排查问题可能原因解决方法扫描不到设备权限未授予检查应用设置里的权限扫描不到设备设备不支持星闪确认是华为星闪设备连接失败设备已被其他手机连接断开其他连接后重试读写失败UUID 不对检查服务UUID和属性UUID8.3 写入数据的技巧// 双重写入策略先尝试 WRITE失败后尝试 WRITE_NO_RESPONSEpublicasyncsendData(serviceId:string,propId:string,data:ArrayBuffer):Promiseboolean{try{// 第一次尝试带响应的写入awaitthis.ssapClient?.writeProperty(prop,ssap.PropertyWriteType.WRITE);returntrue;}catch(error){try{// 第二次尝试不带响应的写入awaitthis.ssapClient?.writeProperty(prop,ssap.PropertyWriteType.WRITE_NO_RESPONSE);returntrue;}catch(e){returnfalse;}}}九、学习资源? 官方星闪开发指南? NearLink Kit API 文档? SSAP 客户端开发十、常见问题 FAQQ1: 我的设备支持星闪吗如何确认HarmonyOS 6设备下拉控制中心检查WLAN下方是不是有星闪标识Q2: 星闪和蓝牙可以同时用吗可以它们使用不同的无线频段互不干扰。你可以同时连接一个蓝牙设备和一个星闪设备。Q4: 星闪设备在哪买目前星闪设备还不太普及可以购买WS63或者BS21E开发板作为初体验作者声明个人拙作仅总结了本人开发经验专业性指导请参考官方文档欢迎各位大佬斧正。本文档不是最简星闪调试工具开发文档代码截取自成熟应用欢迎下载易管闪联星闪端蓝牙端正在突破3.5体验。