1# 远端状态订阅开发实例 2 3IPC/RPC提供对远端Stub对象状态的订阅机制,在远端Stub对象消亡时,可触发消亡通知告诉本地Proxy对象。这种状态通知订阅需要调用特定接口完成,当不再需要订阅时也需要调用特定接口取消。使用这种订阅机制的用户,需要实现消亡通知接口DeathRecipient并实现onRemoteDied方法清理资源。该方法会在远端Stub对象所在进程消亡或所在设备离开组网时被回调。值得注意的是,调用这些接口有一定的顺序。首先,需要Proxy订阅Stub消亡通知,若在订阅期间Stub状态正常,则在不再需要时取消订阅;若在订阅期间Stub所在进程退出或者所在设备退出组网,则会自动触发Proxy自定义的后续操作。 4 5## 使用场景 6 7这种订阅机制适用于本地Proxy对象需要感知远端Stub对象所在进程消亡,或所在设备离开组网的场景。当Proxy感知到Stub端消亡后,可适当清理本地资源。此外,RPC目前不提供匿名Stub对象的消亡通知,即只有向SAMgr注册过的服务才能被订阅消亡通知,IPC则支持匿名对象的消亡通知。 8 9 10## Native侧接口 11 12| 接口名 | 返回值类型 | 功能描述 | 13| -------- | -------- | -------- | 14| AddDeathRecipient(const sptr\<DeathRecipient> &recipient); | bool | 订阅远端Stub对象状态。 | 15| RemoveDeathRecipient(const sptr\<DeathRecipient> &recipient); | bool | 取消订阅远端Stub对象状态。 | 16| OnRemoteDied(const wptr\<IRemoteObject> &object); | void | 当远端Stub对象死亡时回调。 | 17 18### 参考代码 19 20```C++ 21#include "iremote_broker.h" 22#include "iremote_stub.h" 23 24//定义消息码 25enum { 26 TRANS_ID_PING_ABILITY = 5, 27 TRANS_ID_REVERSED_MONITOR 28}; 29 30const std::string DESCRIPTOR = "test.ITestAbility"; 31 32class ITestService : public IRemoteBroker { 33public: 34 // DECLARE_INTERFACE_DESCRIPTOR是必需的,入参需使用std::u16string; 35 DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR)); 36 virtual int TestPingAbility(const std::u16string &dummy) = 0; // 定义业务函数 37}; 38 39class TestServiceProxy : public IRemoteProxy<ITestAbility> { 40public: 41 explicit TestAbilityProxy(const sptr<IRemoteObject> &impl); 42 virtual int TestPingAbility(const std::u16string &dummy) override; 43 int TestAnonymousStub(); 44private: 45 static inline BrokerDelegator<TestAbilityProxy> delegator_; // 方便后续使用iface_cast宏 46}; 47 48TestServiceProxy::TestServiceProxy(const sptr<IRemoteObject> &impl) 49 : IRemoteProxy<ITestAbility>(impl) 50{ 51} 52 53int TestServiceProxy::TestPingAbility(const std::u16string &dummy){ 54 MessageOption option; 55 MessageParcel dataParcel, replyParcel; 56 dataParcel.WriteString16(dummy); 57 int error = PeerHolder::Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); 58 int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; 59 return result; 60} 61``` 62 63```c++ 64#include "iremote_object.h" 65 66class TestDeathRecipient : public IRemoteObject::DeathRecipient { 67public: 68 virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject); 69} 70 71void TestDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remoteObject) 72{ 73} 74``` 75 76```c++ 77sptr<IPCObjectProxy> object = new IPCObjectProxy(1, to_utf16(DESCRIPTOR)); 78sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient());// 构造一个消亡通知对象 79bool result = object->AddDeathRecipient(deathRecipient); // 注册消亡通知 80result = object->RemoveDeathRecipient(deathRecipient); // 移除消亡通知 81``` 82 83## JS侧接口 84 85| 接口名 | 返回值类型 | 功能描述 | 86| ------------------------ | ---------- | ----------------------------------------------------------------- | 87| registerDeathRecipient | void | 注册用于接收远程对象消亡通知的回调,增加 proxy 对象上的消亡通知。 | 88| unregisterDeathRecipient | void | 注销用于接收远程对象消亡通知的回调。 | 89| onRemoteDied | void | 在成功添加死亡通知订阅后,当远端对象死亡时,将自动调用本方法。 | 90 91### 获取context 92 93Stage模型在连接服务前需要先获取context 94 95```ts 96import Ability from "@ohos.app.ability.UIAbility"; 97 98export default class MainAbility extends Ability { 99 onCreate(want, launchParam) { 100 console.log("[Demo] MainAbility onCreate"); 101 globalThis.context = this.context; 102 } 103 onDestroy() { 104 console.log("[Demo] MainAbility onDestroy"); 105 } 106 onWindowStageCreate(windowStage) { 107 // Main window is created, set main page for this ability 108 console.log("[Demo] MainAbility onWindowStageCreate"); 109 } 110 onWindowStageDestroy() { 111 // Main window is destroyed, release UI related resources 112 console.log("[Demo] MainAbility onWindowStageDestroy"); 113 } 114 onForeground() { 115 // Ability has brought to foreground 116 console.log("[Demo] MainAbility onForeground"); 117 } 118 onBackground() { 119 // Ability has back to background 120 console.log("[Demo] MainAbility onBackground"); 121 } 122} 123``` 124 125### 参考代码 126 127```ts 128// 仅FA模型需要导入@ohos.ability.featureAbility 129// import FA from "@ohos.ability.featureAbility"; 130 131let proxy; 132let connect = { 133 onConnect: function(elementName, remoteProxy) { 134 console.log("RpcClient: js onConnect called."); 135 proxy = remoteProxy; 136 }, 137 onDisconnect: function(elementName) { 138 console.log("RpcClient: onDisconnect"); 139 }, 140 onFailed: function() { 141 console.log("RpcClient: onFailed"); 142 } 143}; 144let want = { 145 "bundleName": "com.ohos.server", 146 "abilityName": "com.ohos.server.MainAbility", 147}; 148// FA模型通过此方法连接服务 149// FA.connectAbility(want, connect); 150 151globalThis.context.connectServiceExtensionAbility(want, connect); 152 153class MyDeathRecipient { 154 onRemoteDied() { 155 console.log("server died"); 156 } 157} 158let deathRecipient = new MyDeathRecipient(); 159proxy.registerDeathRecippient(deathRecipient, 0); 160proxy.unregisterDeathRecipient(deathRecipient, 0); 161``` 162 163## Stub感知Proxy消亡(匿名Stub的使用) 164 165正向的消亡通知是Proxy感知Stub的状态,若想达到反向的死消亡通知,即Stub感知Proxy的状态,可以巧妙的利用正向消亡通知。如两个进程A(原Stub所在进程)和B(原Proxy所在进程),进程B在获取到进程A的Proxy对象后,在B进程新建一个匿名Stub对象(匿名指未向SAMgr注册),可称之为回调Stub,再通过SendRequest接口将回调Stub传给进程A的原Stub。这样一来,进程A便获取到了进程B的回调Proxy。当进程B消亡或B所在设备离开组网时,回调Stub会消亡,回调Proxy会感知,进而通知给原Stub,便实现了反向消亡通知。 166 167注意: 168 169> 反向死亡通知仅限设备内跨进程通信使用,不可用于跨设备。 170 171> 当匿名Stub对象没有被任何一个Proxy指向的时候,内核会自动回收。 172 173### 参考代码 174 175```c++ 176//Proxy 177int TestAbilityProxy::TestAnonymousStub() 178{ 179 MessageOption option; 180 MessageParcel dataParcel, replyParcel; 181 dataParcel.UpdateDataVersion(Remote()); 182 dataParcel.WriteRemoteObject(new TestAbilityStub()); 183 int error = Remote()->SendRequest(TRANS_ID_REVERSED_MONITOR,dataParcel, replyParcel, option); 184 int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; 185 return result; 186} 187 188//Stub 189 190int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) 191{ 192 switch (code) { 193 case TRANS_ID_REVERSED_MONITOR: { 194 sptr<IRemoteObject> obj = data.ReadRemoteObject(); 195 if (obj == nullptr) { 196 reply.WriteInt32(ERR_NULL_OBJECT); 197 return ERR_NULL_OBJECT; 198 } 199 bool result = obj->AddDeathRecipient(new TestDeathRecipient()); 200 result ? reply.WriteInt32(ERR_NONE) : reply.WriteInt32(-1); 201 break; 202 } 203 default: 204 break; 205 } 206 return ERR_NONE; 207} 208``` 209 210