• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Subscribing to State Changes of a Remote Object
2
3IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
4
5## Scenarios
6
7This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr.
8
9
10## Native APIs
11
12| Name                                                             |  Description                    |
13| ------------------------------------------------------------------- | ------------------------- |
14| bool AddDeathRecipient(const sptr\<DeathRecipient> &recipient);     | Adds a recipient for death notifications of a remote stub object.    |
15| bool RemoveDeathRecipient(const sptr\<DeathRecipient> &recipient);  | Removes the recipient for death notifications of a remote stub object.|
16| void OnRemoteDied(const wptr\<IRemoteObject> &object);              | Called when the remote stub object dies.|
17
18### Sample Code
19
20```C++
21#include "iremote_broker.h"
22#include "iremote_stub.h"
23
24// Define message codes.
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 is mandatory, and the input parameter is std::u16string.
35    DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR));
36    virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
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_; // For use of the iface_cast macro at a later time
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()); // Construct a death notification recipient.
79bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
80result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
81```
82
83## ArkTS APIs
84
85| Name                                                      | Return Value Type| Description                                                    |
86| ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ |
87| [registerDeathRecipient](../reference/apis/js-apis-rpc.md#registerdeathrecipient9-1) | void       | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.|
88| [unregisterDeathRecipient](../reference/apis/js-apis-rpc.md#unregisterdeathrecipient9-1) | void       | Removes the recipient for death notifications of the remote object.                        |
89| [onRemoteDied](../reference/apis/js-apis-rpc.md#onremotedied) | void       | Called to perform subsequent operations when a death notification of the remote object is received.|
90
91### Obtaining the Context
92
93If you use the stage model, you need to obtain the context before connecting to an ability.
94
95```ts
96import UIAbility from '@ohos.app.ability.UIAbility';
97import Want from '@ohos.app.ability.Want';
98import hilog from '@ohos.hilog';
99import AbilityConstant from '@ohos.app.ability.AbilityConstant';
100import window from '@ohos.window';
101
102export default class MainAbility extends UIAbility {
103  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
104    hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onCreate');
105    let context = this.context;
106  }
107  onDestroy() {
108    hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onDestroy');
109  }
110  onWindowStageCreate(windowStage: window.WindowStage) {
111    // Main window is created, set main page for this ability
112  	hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onWindowStageCreate');
113  }
114  onWindowStageDestroy() {
115    // Main window is destroyed, release UI related resources
116  	hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onWindowStageDestroy');
117  }
118  onForeground() {
119    // Ability has brought to foreground
120    hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onForeground');
121  }
122  onBackground() {
123    // Ability has back to background
124    hilog.info(0x0000, 'testTag', '%{public}s', 'UIAbility onBackground');
125  }
126}
127```
128
129### Sample Code
130
131```ts
132// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
133// import FA from "@ohos.ability.featureAbility";
134import Want from '@ohos.app.ability.Want';
135import common from '@ohos.app.ability.common';
136import rpc from '@ohos.rpc';
137import hilog from '@ohos.hilog';
138
139let proxy: rpc.IRemoteObject | undefined;
140let connect: common.ConnectOptions = {
141  onConnect: (elementName, remoteProxy) => {
142    hilog.info(0x0000, 'testTag', 'RpcClient: js onConnect called.');
143    proxy = remoteProxy;
144  },
145  onDisconnect: (elementName) => {
146    hilog.info(0x0000, 'testTag', 'RpcClient: onDisconnect');
147  },
148  onFailed: () => {
149    hilog.info(0x0000, 'testTag', 'RpcClient: onFailed');
150  }
151};
152let want: Want = {
153  bundleName: "com.ohos.server",
154  abilityName: "com.ohos.server.EntryAbility",
155};
156// Use this method to connect to the ability in the FA model.
157// FA.connectAbility(want, connect);
158
159this.context.connectServiceExtensionAbility(want, connect);
160```
161
162The **proxy** object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. After that, [unregisterDeathRecipient](../reference/apis/js-apis-rpc.md#unregisterdeathrecipient9-1) of the **proxy** object can be called to unregister the callback for receiving the death notification of the remote object.
163
164```ts
165import rpc from '@ohos.rpc';
166import hilog from '@ohos.hilog';
167
168class MyDeathRecipient implements rpc.DeathRecipient{
169  onRemoteDied() {
170    hilog.info(0x0000, 'testTag', 'server died');
171  }
172}
173let deathRecipient = new MyDeathRecipient();
174if (proxy != undefined) {
175  proxy.registerDeathRecipient(deathRecipient, 0);
176  proxy.unregisterDeathRecipient(deathRecipient, 0);
177}
178```
179
180## Reverse Death Notification (Anonymous Stub)
181
182Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy. Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented.
183
184**NOTE**
185
186> Reverse death notification can only be used for cross-process communication within a device.
187
188> When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object.
189
190### Sample Code
191
192```c++
193// Proxy
194int TestAbilityProxy::TestAnonymousStub()
195{
196    MessageOption option;
197    MessageParcel dataParcel, replyParcel;
198    dataParcel.UpdateDataVersion(Remote());
199    dataParcel.WriteRemoteObject(new TestAbilityStub());
200    int error = Remote()->SendRequest(TRANS_ID_REVERSED_MONITOR,dataParcel, replyParcel, option);
201    int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
202    return result;
203}
204
205// Stub
206
207int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
208{
209    switch (code) {
210        case TRANS_ID_REVERSED_MONITOR: {
211            sptr<IRemoteObject> obj = data.ReadRemoteObject();
212            if (obj == nullptr) {
213                reply.WriteInt32(ERR_NULL_OBJECT);
214                return ERR_NULL_OBJECT;
215            }
216            bool result = obj->AddDeathRecipient(new TestDeathRecipient());
217            result ? reply.WriteInt32(ERR_NONE) : reply.WriteInt32(-1);
218            break;
219        }
220        default:
221            break;
222    }
223    return ERR_NONE;
224}
225```
226