当前位置: 首页 > 科技观察

HarmonyOSSample的ServiceAbility跨设备接口调用

时间:2023-03-20 23:25:10 科技观察

更多内容请访问:Harmonyos技术社区https://harmonyos.51cto.comServiceAbility跨设备接口调用介绍本示例演示ServiceAbilityStart、stop、connect、disconnect等操作,支持ServiceAbility跨设备运行。您将学习到以下三个知识点:1.IDL的使用,以及IPC方法的调用2.前台Service的使用3.EventHandle事件处理的使用搭建环境,安装DevEcoStudio。具体请参考DevEcoStudio下载。搭建DevEcoStudio开发环境。DevEcoStudio开发环境依赖于网络环境。需要联网才能保证工具的正常使用。开发环境可根据以下两种情况进行配置:如果可以直接上网,只需要下载HarmonyOSSDK即可运行。如果网络不能直接访问Internet,则需要通过代理服务器访问。请参考配置开发环境。代码结构解释后台逻辑│config.json#全局配置文件│├─idl│└─ohos│└─samples└─serviceability│IRemoteAgent.idl#提供远程接口idl文件│├─java│└─ohos│└─samples│└─serviceability││ForegroundServiceAbility.java#前台ServiceAbility││LocalServiceAbility.java#模拟本地ServiceAbility││MainAbility.java││RemoteAbility.java#模拟远程ServiceAbility││└─slice│MainAbilitySlice.java#的页面布局文件主能力页面只有一个main_slice.xml页面布局和三个知识点1、IDL的使用和IPC方法的调用术语:客户端和服务端通信时,需要定义一个双方都认可的接口为确保双方能够成功通信,HarmonyOSIDL(HarmonyOSInterfaceDefinitionLanguage)是定义此类接口的工具。Inter-processcall(IPC)进程间通信或设备间调用(RPC)远程过程调用IDL接口规范:https://developer.harmonyos.com/cn/docs/documentation/doc-references/idl-overview-0000001050762835首先声明权限,敏感权限也需要请求用户授权,在之前的文章中都有写,这里就不写了。"reqPermissions":[{"name":"ohos.permission.GET_DISTRIBUTED_DEVICE_INFO"},...{"name":"ohos.permission.DISTRIBUTED_DATASYNC"}]a.创建.idl文件IRemoteAgent.idl//Declareanynon-defaulttypesherewithsequenceableorinterfacestatementsinterfaceohos.samples.serviceability.IRemoteAgent{/**Demoservicemethodusesomeparameters*/voidsetRemoteObject([in]Stringparam);}b.编译idl文件,生成相应的接口类、存根类和代理类c。serverIDL的实现privatestaticfinalStringDESCRIPTOR="ohos.samples.serviceability.RemoteAbility";//idlserver的实现,RemoteAgentStubremoteAgentStub=newRemoteAgentStub(DESCRIPTOR){@OverridepublicvoidsetRemoteObject(Stringparam){HiLog.info(LABEL_LOG,"%{public}s","setRemoteObject:"+param);//不能这样,使用下面的通知方式//showTips(RemoteAbility.this,param);//赋值param_mess=param;//事件通知eventHandler.sendEvent(EVENT_ABILITY_MESS);}};d.Client调用IPC方法//IDL代理类privateRemoteAgentProxyremoteAgentProxy;/***ConnectService*@paramisConnectRemote*/privatevoidconnectService(booleanisConnectRemote){//一个三元表达式,用于确定是本地连接还是远程连接。isConnect&&remoteAgentProxy!=null){try{//调用服务端IPC方法remoteAgentProxy.setRemoteObject("Thisparamfromclient");}catch(RemoteExceptione){HiLog.error(LABEL_LOG,"%{public}s","onAbilityConnectDoneRemoteException");}}}//建立连接并实例化代理对象proxyobjectremoteAgentProxy=newRemoteAgentProxy(iRemoteObject);}@OverridepublicvoidonAbilityDisconnectDone(ElementNameelementName,intresultCode){//发送Service断开的通知,不会执行主动断开,eventHandler.sendEvent(EVENT_ABILITY_DISCONNECT_DONE);}};2。如何使用前台服务a.权限声明:"reqPermissions":[{"name":"ohos.permission.KEEP_BACKGROUND_RUNNING"},...]b。设置通知栏的内容,然后,在onStart方法中调用keepBackgroundRunning方法,让这个服务能力一直在后台显示通知栏。在onStop方法中调用cancelBackgroundRunning()方法取消该函数的后台运行,释放系统内存。//通知IDprivatestaticfinalintNOTIFICATION_ID=0XD0000002;@OverrideprotectedvoidonStart(Intentintent){//调用方法startForeground();super.onStart(intent);}@OverrideprotectedvoidonStop(){super.onStop();//取消本函数的后台运行释放系统内存。cancelBackgroundRunning();}/***保持这个服务能力在后台,显示通知栏。*/privatevoidstartForeground(){HiLog.info(LABEL_LOG,"startForeground");//任务栏显示通知cardhasbeenremovedaccidentally").setText("请卸载记忆卡后再取出,以免数据丢失");content.setAdditionalText("21分钟前");//设置通知栏ContentNotificationRequest.NotificationContentnotificationContent=newNotificationRequest.NotificationContent(content);request.setContent(notificationContent);//后台预留该服务能力,显示通知栏。keepBackgroundRunning(NOTIFICATION_ID,request);}3.如何使用EventHandle事件处理EventHandler将事件或Runnable任务传递给线程的事件队列,当事件或任务从事件队列中出来时执行。您可以使用EventHandler跨不同线程调度和处理事件和Runnable对象,并调度事件或Runnable对象在特定时间间隔处理。您可以使用此类中提供的方法发送同步或异步事件、延迟事件处理和设置事件优先级。//定义事件IDprivatestaticfinalintEVENT_ABILITY_CONNECT_DONE=0x1000001;privatestaticfinalintEVENT_ABILITY_DISCONNECT_DONE=0x1000002;privateEventHandlereventHandler=newEventHandler(EventRunner.current()){@OverrideprotectedvoidprocessEvent(InnerEventevent){switch(event.eventId){caseEVENT_ABILITY_CONNECT_DONE:showTips(MainAbilitySlice.this,"Serviceconnectsucceeded");break;caseEVENT_ABILITY_DISCONNECT_DONE:showTips(MainAbilitySlice.this,"Servicedisconnectsucceeded");break;default:break;}}};//发送Service连接成功的通知eventHandler.sendEvent(EVENT_ABILITY_CONNECT_DONE);附件可点击下方原文链接下载:https://harmonyos.51cto.com/posts/4776更多内容请访问:与华为官方共建的鸿蒙技术社区https://harmonyos。51cto.com