• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.distributedHardware.deviceManager (Device Management)
2
3The APIs of this module are deprecated. You are advised to use the APIs of the [@ohos.distributedDeviceManager](js-apis-distributedDeviceManager.md) module instead.
4
5The **deviceManager** module provides APIs for distributed device management.
6
7System applications can call the APIs to do the following:
8
9- Subscribe to or unsubscribe from device state changes.
10- Discover peripheral untrusted devices.
11- Authenticate or deauthenticate a device.
12- Query the trusted device list.
13- Query local device information, including the device name, type, and ID.
14- Publish device information for discovery purposes.
15
16> **NOTE**
17>
18> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
19> - The APIs of this module are system APIs and cannot be called by third-party applications.
20
21
22## Modules to Import
23
24```ts
25import deviceManager from '@ohos.distributedHardware.deviceManager';
26```
27
28
29## deviceManager.createDeviceManager
30
31createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager>): void
32
33Creates a **DeviceManager** instance.
34
35**System capability**: SystemCapability.DistributedHardware.DeviceManager
36
37**Parameters**
38
39| Name    | Type                                                | Mandatory| Description                                                       |
40| ---------- | ---------------------------------------------------- | ---- | ----------------------------------------------------------- |
41| bundleName | string                                               | Yes  | Bundle name of the application.                                 |
42| callback   | AsyncCallback<[DeviceManager](#devicemanager)> | Yes  | Callback invoked to return the **DeviceManager** instance created.|
43
44**Example**
45
46  ```ts
47  import deviceManager from '@ohos.distributedHardware.deviceManager';
48  import { BusinessError } from '@ohos.base'
49
50  let dmInstance: deviceManager.Devicemanager | null = null;
51  try {
52    deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err: BusinessError, data: deviceManager.Devicemanager) => {
53      if (err) {
54        console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
55        return;
56      }
57      console.info("createDeviceManager success");
58      dmInstance = data;
59    });
60  } catch(err) {
61    let e: BusinessError = err as BusinessError;
62    console.error("createDeviceManager errCode:" + e.code + ",errMessage:" + e.message);
63  }
64  ```
65
66## DeviceInfo
67
68Defines device information.
69
70**System capability**: SystemCapability.DistributedHardware.DeviceManager
71
72| Name                    | Type                       | Mandatory  | Description      |
73| ---------------------- | ------------------------- | ---- | -------- |
74| deviceId               | string                    | Yes   | Unique identifier of the device.|
75| deviceName             | string                    | Yes   | Device name.   |
76| deviceType             | [DeviceType](#devicetype) | Yes   | Device type.   |
77| networkId<sup>8+</sup> | string                    | Yes   | Network ID of the device. |
78| range<sup>9+</sup>     | number                    | Yes   | Distance between the device (discovered device) and the device that initiates device discovery. |
79| authForm<sup>10+</sup> | [AuthForm](#authform)     | Yes   | Authentication type of the device. |
80
81## DeviceType
82
83Enumerates the device types.
84
85**System capability**: SystemCapability.DistributedHardware.DeviceManager
86
87| Name          | Value | Description  |
88| ------------ | ---- | ---- |
89| SPEAKER      | 0x0A | Smart speaker.|
90| PHONE        | 0x0E | Phone.  |
91| TABLET       | 0x11 | Tablet.  |
92| WEARABLE     | 0x6D | Wearable.|
93| TV           | 0x9C | Smart TV. |
94| CAR          | 0x83 | Car.   |
95| UNKNOWN_TYPE | 0    | Unknown device type.|
96
97## AuthForm<sup>10+</sup>
98
99Enumerates the device authentication types.
100
101**System capability**: SystemCapability.DistributedHardware.DeviceManager
102
103| Name                | Value | Description            |
104| ------------------- | ---- | --------------- |
105| INVALID_TYPE        | -1   | No authentication.|
106| PEER_TO_PEER        | 0    | Point-to-point authentication for devices without accounts.  |
107| IDENTICAL_ACCOUNT   | 1    | Authentication for devices using the same account.  |
108| ACROSS_ACCOUNT      | 2    | Authentication for devices using different accounts.|
109
110## DeviceStateChangeAction
111
112Enumerates the device states.
113
114**System capability**: SystemCapability.DistributedHardware.DeviceManager
115
116| Name     | Value | Description             |
117| ------- | ---- | --------------- |
118| ONLINE  | 0    | The device is physically online.          |
119| READY   | 1    | The information between devices has been synchronized in the Distributed Data Service (DDS) module, and the device is ready for running distributed services.|
120| OFFLINE | 2    | The device is physically offline.          |
121| CHANGE  | 3    | The device information is changed.        |
122
123## SubscribeInfo
124
125Defines subscription information.
126
127**System capability**: SystemCapability.DistributedHardware.DeviceManager
128
129| Name           | Type                               | Mandatory  | Description               |
130| ------------- | --------------------------------- | ---- | ----------------- |
131| subscribeId   | number                            | Yes   | Subscription ID, used to identify a device discovery period.|
132| mode          | [DiscoverMode ](#discovermode)    | Yes   | Device discovery mode.            |
133| medium        | [ExchangeMedium](#exchangemedium) | Yes   | Medium used for device discovery.            |
134| freq          | [ExchangeFreq](#exchangefreq)     | Yes   | Frequency of device discovery.            |
135| isSameAccount | boolean                           | No   | Whether the same account is used on the discovered device.           |
136| isWakeRemote  | boolean                           | No   | Whether to wake up the discovered device.          |
137| capability    | [SubscribeCap](#subscribecap)     | Yes   | Discovery capability.            |
138
139
140## DiscoverMode
141
142Enumerates the device discovery modes.
143
144**System capability**: SystemCapability.DistributedHardware.DeviceManager
145
146| Name                   | Value | Description   |
147| --------------------- | ---- | ----- |
148| DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.|
149| DISCOVER_MODE_ACTIVE  | 0xAA | Active discovery.|
150
151
152## ExchangeMedium
153
154Enumerates the media used for device discovery.
155
156**System capability**: SystemCapability.DistributedHardware.DeviceManager
157
158| Name  | Value | Description       |
159| ---- | ---- | --------- |
160| AUTO | 0    | Automatic.  |
161| BLE  | 1    | Bluetooth.  |
162| COAP | 2    | Wi-Fi.|
163| USB  | 3    | USB. |
164
165## ExchangeFreq
166
167Enumerates the device discovery frequencies.
168
169**System capability**: SystemCapability.DistributedHardware.DeviceManager
170
171| Name        | Value | Description   |
172| ---------- | ---- | ----- |
173| LOW        | 0    | Low frequency. |
174| MID        | 1    | Medium frequency. |
175| HIGH       | 2    | High frequency. |
176| SUPER_HIGH | 3    | Ultra-high frequency.|
177
178
179## SubscribeCap
180
181Enumerates the discovery capabilities.
182
183**System capability**: SystemCapability.DistributedHardware.DeviceManager
184
185| Name                       | Value | Description            |
186| ------------------------- | ---- | -------------- |
187| SUBSCRIBE_CAPABILITY_DDMP | 0    | DDMP capability. This will be deprecated later.|
188| SUBSCRIBE_CAPABILITY_OSD  | 1    | OSD capability.        |
189
190
191## AuthParam
192
193Defines the authentication parameters.
194
195**System capability**: SystemCapability.DistributedHardware.DeviceManager
196
197| Name       | Type                  | Mandatory  | Description        |
198| --------- | -------------------- | ---- | ---------- |
199| authType  | number               | Yes   | Authentication type.     |
200| extraInfo | {[key:string]&nbsp;:&nbsp;any} | No   | Extended field. Optional. The default value is **undefined**.|
201
202## AuthInfo
203
204Defines authentication information.
205
206**System capability**: SystemCapability.DistributedHardware.DeviceManager
207
208| Name       | Type                  | Mandatory  | Description        |
209| --------- | -------------------- | ---- | ---------- |
210| authType  | number               | Yes   | Authentication type.     |
211| token     | number               | Yes   | Authentication token.  |
212| extraInfo | {[key:string]&nbsp;:&nbsp;any} | No   | Extended field. Optional. The default value is **undefined**.|
213
214## PublishInfo<sup>9+</sup>
215
216Defines published device information.
217
218**System capability**: SystemCapability.DistributedHardware.DeviceManager
219
220| Name         | Type                             | Mandatory  | Description               |
221| ------------- | --------------------------------- | ---- | ----------------- |
222| publishId     | number                            | Yes   | ID used to identify a publication period.|
223| mode          | [DiscoverMode ](#discovermode)    | Yes   | Device discovery mode.            |
224| freq          | [ExchangeFreq](#exchangefreq)     | Yes   | Frequency of device discovery.            |
225| ranging       | boolean                           | Yes   | Whether the device supports distance reporting.            |
226
227## DeviceManager
228
229Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**.
230
231### release
232
233release(): void
234
235Releases this **DeviceManager** instance when it is no longer used.
236
237**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
238
239**System capability**: SystemCapability.DistributedHardware.DeviceManager
240
241**Error codes**
242
243For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
244
245| ID| Error Message                                                       |
246| -------- | --------------------------------------------------------------- |
247| 11600101 | Failed to execute the function.                                 |
248
249**Example**
250
251  ```ts
252  import { BusinessError } from '@ohos.base'
253
254  try {
255    dmInstance.release();
256  } catch (err) {
257    let e: BusinessError = err as BusinessError;
258    console.error("release errCode:" + e.code + ",errMessage:" + e.message);
259  }
260  ```
261
262### getTrustedDeviceListSync
263
264getTrustedDeviceListSync(): Array&lt;DeviceInfo&gt;
265
266Obtains all trusted devices synchronously.
267
268**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
269
270**System capability**: SystemCapability.DistributedHardware.DeviceManager
271
272**Return value**
273
274| Name                                    | Description       |
275| -------------------------------------- | --------- |
276| Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of trusted devices obtained.|
277
278**Error codes**
279
280For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
281
282| ID| Error Message                                                       |
283| -------- | --------------------------------------------------------------- |
284| 11600101 | Failed to execute the function.                                 |
285
286**Example**
287
288  ```ts
289  import deviceManager from '@ohos.distributedHardware.deviceManager';
290  import { BusinessError } from '@ohos.base'
291
292  try {
293    let deviceInfoList: Array<deviceManager.DeviceInfo> = dmInstance.getTrustedDeviceListSync();
294  } catch (err) {
295    let e: BusinessError = err as BusinessError;
296    console.error("getTrustedDeviceListSync errCode:" + e.code + ",errMessage:" + e.message);
297  }
298  ```
299
300### getTrustedDeviceListSync<sup>10+</sup>
301
302getTrustedDeviceListSync(isRefresh: boolean): Array&lt;DeviceInfo&gt;
303
304Enables the DSoftBus heartbeat mode to quickly bring offline trusted devices online and updates the list of online trusted devices.
305
306**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
307
308**System capability**: SystemCapability.DistributedHardware.DeviceManager
309
310**Parameters**
311
312| Name       | Type                              | Mandatory| Description                               |
313| ------------- | --------------------------------- | ---- | ---------------------------------- |
314|   isRefresh   | boolean                           | Yes  | Whether to enable the heartbeat mode and update the list of online trusted devices.     |
315
316**Return value**
317
318| Name                                    | Description           |
319| -------------------------------------- | ---------------- |
320| Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of trusted devices obtained.|
321
322**Error codes**
323
324For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
325
326| ID| Error Message                                                        |
327| -------- | --------------------------------------------------------------- |
328| 11600101 | Failed to execute the function.                                 |
329
330**Example**
331
332  ```ts
333  import deviceManager from '@ohos.distributedHardware.deviceManager';
334  import { BusinessError } from '@ohos.base'
335
336  try {
337    let deviceInfoList: Array<deviceManager.DeviceInfo> = dmInstance.getTrustedDeviceListSync(true);
338  } catch (err) {
339    let e: BusinessError = err as BusinessError;
340    console.error("getTrustedDeviceListSync errCode:" + e.code + ",errMessage:" + e.message);
341  }
342  ```
343
344### getTrustedDeviceList<sup>8+</sup>
345
346getTrustedDeviceList(callback:AsyncCallback&lt;Array&lt;DeviceInfo&gt;&gt;): void
347
348Obtains all trusted devices. This API uses an asynchronous callback to return the result.
349
350**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
351
352**System capability**: SystemCapability.DistributedHardware.DeviceManager
353
354**Parameters**
355
356| Name      | Type                                    | Mandatory  | Description                   |
357| -------- | ---------------------------------------- | ---- | --------------------- |
358| callback | AsyncCallback&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Yes   | Callback invoked to return the list of trusted devices.|
359
360**Example**
361
362  ```ts
363  import deviceManager from '@ohos.distributedHardware.deviceManager';
364  import { BusinessError } from '@ohos.base'
365  try {
366    dmInstance.getTrustedDeviceList((err: BusinessError, data: deviceManager.DeviceInfo) => {
367      if (err) {
368        console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
369        return;
370      }
371      console.log('get trusted device info: ' + JSON.stringify(data));
372    });
373  } catch (err) {
374    let e: BusinessError = err as BusinessError;
375    console.error("getTrustedDeviceList errCode:" + e.code + ",errMessage:" + e.message);
376  }
377  ```
378
379### getTrustedDeviceList<sup>8+</sup>
380
381getTrustedDeviceList(): Promise&lt;Array&lt;DeviceInfo&gt;&gt;
382
383Obtains all trusted devices. This API uses a promise to return the result.
384
385**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
386
387**System capability**: SystemCapability.DistributedHardware.DeviceManager
388
389**Return value**
390
391| Type                                      | Description                   |
392| ---------------------------------------- | --------------------- |
393| Promise&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Promise used to return the result.|
394
395**Example**
396
397  ```ts
398  import deviceManager from '@ohos.distributedHardware.deviceManager';
399  import { BusinessError } from '@ohos.base'
400
401  dmInstance.getTrustedDeviceList().then((data: Array<deviceManager.DeviceInfo>) => {
402    console.log('get trusted device info: ' + JSON.stringify(data));
403    }).catch((err: BusinessError) => {
404      console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
405  });
406  ```
407
408### getLocalDeviceInfoSync<sup>8+</sup>
409
410getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo)
411
412Obtains local device information synchronously.
413
414**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
415
416**System capability**: SystemCapability.DistributedHardware.DeviceManager
417
418**Return value**
419
420| Name                     | Description             |
421| ------------------------- | ---------------- |
422| [DeviceInfo](#deviceinfo) | List of local devices obtained.|
423
424**Error codes**
425
426For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
427
428| ID| Error Message                                                       |
429| -------- | --------------------------------------------------------------- |
430| 11600101 | Failed to execute the function.                                 |
431
432**Example**
433
434  ```ts
435  import deviceManager from '@ohos.distributedHardware.deviceManager';
436  import { BusinessError } from '@ohos.base'
437
438  try {
439    let deviceInfo: deviceManager.DeviceInfo = dmInstance.getLocalDeviceInfoSync();
440  } catch (err) {
441    let e: BusinessError = err as BusinessError;
442    console.error("getLocalDeviceInfoSync errCode:" + e.code + ",errMessage:" + e.message);
443  }
444  ```
445
446### getLocalDeviceInfo<sup>8+</sup>
447
448getLocalDeviceInfo(callback:AsyncCallback&lt;DeviceInfo&gt;): void
449
450Obtains local device information. This API uses an asynchronous callback to return the result.
451
452**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
453
454**System capability**: SystemCapability.DistributedHardware.DeviceManager
455
456**Parameters**
457
458| Name      | Type                                    | Mandatory  | Description       |
459| -------- | ---------------------------------------- | ---- | --------- |
460| callback | AsyncCallback&lt;[DeviceInfo](#deviceinfo)&gt; | Yes   | Callback invoked to return the local device information.|
461
462**Example**
463
464  ```ts
465  import deviceManager from '@ohos.distributedHardware.deviceManager';
466  import { BusinessError } from '@ohos.base'
467
468
469  try {
470    dmInstance.getLocalDeviceInfo((err: BusinessError, data: deviceManager.DeviceInfo) => {
471    if (err) {
472      console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
473      return;
474    }
475      console.log('get local device info: ' + JSON.stringify(data));
476    });
477  } catch (err) {
478    let e: BusinessError = err as BusinessError;
479    console.error("getLocalDeviceInfo errCode:" + e.code + ",errMessage:" + e.message);
480  }
481  ```
482
483### getLocalDeviceInfo<sup>8+</sup>
484
485getLocalDeviceInfo(): Promise&lt;DeviceInfo&gt;
486
487Obtains local device information. This API uses a promise to return the result.
488
489**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
490
491**System capability**: SystemCapability.DistributedHardware.DeviceManager
492
493**Return value**
494
495| Type                                      | Description                   |
496| ---------------------------------------- | --------------------- |
497| Promise&lt;[DeviceInfo](#deviceinfo)&gt; | Promise used to return the result.|
498
499**Example**
500
501  ```ts
502  import deviceManager from '@ohos.distributedHardware.deviceManager';
503  import { BusinessError } from '@ohos.base'
504
505  dmInstance.getLocalDeviceInfo().then((data: deviceManager.DeviceInfo) => {
506    console.log('get local device info: ' + JSON.stringify(data));
507  }).catch((err: BusinessError) => {
508    console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
509  });
510  ```
511
512### getDeviceInfo<sup>10+</sup>
513
514getDeviceInfo(networkId: string, callback:AsyncCallback&lt;DeviceInfo&gt;): void
515
516Obtains the information about a specific device based on the network ID. This API uses an asynchronous callback to return the result.
517
518**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
519
520**System capability**: SystemCapability.DistributedHardware.DeviceManager
521
522**Parameters**
523
524| Name      | Type                                    | Mandatory  | Description       |
525| -------- | ---------------------------------------- | ---- | --------- |
526| networkId| string                                   | Yes  | Network ID of the device.|
527| callback | AsyncCallback&lt;[DeviceInfo](#deviceinfo)&gt; | Yes   | Callback invoked to return the information about the specified device.|
528
529**Example**
530
531  ```ts
532  import deviceManager from '@ohos.distributedHardware.deviceManager';
533  import { BusinessError } from '@ohos.base'
534
535  try {
536    // Network ID of the device, which can be obtained from the trusted device list
537    let networkId = "xxxxxxx"
538    dmInstance.getDeviceInfo(networkId, (err: BusinessError, data: deviceManager.DeviceInfo) => {
539    if (err) {
540      console.error("getDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
541      return;
542    }
543      console.log('get device info: ' + JSON.stringify(data));
544    });
545  } catch (err) {
546    let e: BusinessError = err as BusinessError;
547    console.error("getDeviceInfo errCode:" + e.code + ",errMessage:" + e.message);
548  }
549  ```
550
551### getDeviceInfo<sup>10+</sup>
552
553getDeviceInfo(networkId: string): Promise&lt;DeviceInfo&gt;
554
555Obtains the information about a specific device based on the network ID. This API uses a promise to return the result.
556
557**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
558
559**System capability**: SystemCapability.DistributedHardware.DeviceManager
560
561**Parameters**
562
563| Name  | Type                                    | Mandatory| Description       |
564| -------- | ---------------------------------------- | ---- | --------- |
565| networkId| string                                   | Yes  | Network ID of the device.|
566
567**Return value**
568
569| Type                                      | Description                   |
570| ---------------------------------------- | --------------------- |
571| Promise&lt;[DeviceInfo](#deviceinfo)&gt; | Promise used to return the result.|
572
573**Example**
574
575  ```ts
576  import deviceManager from '@ohos.distributedHardware.deviceManager';
577  import { BusinessError } from '@ohos.base'
578
579  // Network ID of the device, which can be obtained from the trusted device list
580  let networkId = "xxxxxxx"
581  dmInstance.getDeviceInfo(networkId).then((data: deviceManager.DeviceInfo) => {
582    console.log('get device info: ' + JSON.stringify(data));
583  }).catch((err: BusinessError) => {
584    console.error("getDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
585  });
586  ```
587
588### startDeviceDiscovery<sup>8+</sup>
589
590startDeviceDiscovery(subscribeInfo: SubscribeInfo): void
591
592Starts to discover peripheral devices. The discovery process automatically stops when 2 minutes have elapsed. A maximum of 99 devices can be discovered.
593
594**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
595
596**System capability**: SystemCapability.DistributedHardware.DeviceManager
597
598**Parameters**
599
600| Name           | Type                      | Mandatory| Description   |
601| ------------- | ------------------------------- | ---- | ----- |
602| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes  | Subscription information.|
603
604**Error codes**
605
606For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
607
608| ID| Error Message                                                       |
609| -------- | --------------------------------------------------------------- |
610| 11600101 | Failed to execute the function.                                 |
611| 11600104 | Discovery invalid.                                              |
612
613**Example**
614
615  ```ts
616  import { BusinessError } from '@ohos.base'
617
618  interface SubscribeInfo {
619    subscribeId: number,
620    mode: number, // Active discovery
621    medium: number,  // Automatic. Multiple media can be used for device discovery.
622    freq: number,    // High frequency
623    isSameAccount: boolean,
624    isWakeRemote: boolean,
625    capability: number
626  };
627
628  // Automatically generate a unique subscription ID.
629  let subscribeId = Math.floor(Math.random() * 10000 + 1000);
630  let subscribeInfo: SubscribeInfo = {
631    subscribeId: subscribeId,
632    mode: 0xAA, // Active discovery
633    medium: 0,  // Automatic. Multiple media can be used for device discovery.
634    freq: 2,    // High frequency
635    isSameAccount: false,
636    isWakeRemote: false,
637    capability: 1
638  };
639  try {
640    dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is called to notify the application when a device is discovered.
641  } catch (err) {
642    let e: BusinessError = err as BusinessError;
643    console.error("startDeviceDiscovery errCode:" + e.code + ",errMessage:" + e.message);
644  }
645  ```
646
647### startDeviceDiscovery<sup>9+</sup>
648
649startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void
650
651Starts to discover peripheral devices and filters discovered devices. The discovery process automatically stops when 2 minutes have elapsed. A maximum of 99 devices can be discovered.
652
653**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
654
655**System capability**: SystemCapability.DistributedHardware.DeviceManager
656
657**Parameters**
658
659| Name           | Type                      | Mandatory  | Description   |
660| ------------- | ------------------------------- | ---- | -----  |
661| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes  | Subscription information.|
662| filterOptions | string                          | No  | Options for filtering discovered devices. Optional. The default value is **undefined**, which indicates discovery of offline devices.|
663
664**Error codes**
665
666For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
667
668| ID| Error Message                                                       |
669| -------- | --------------------------------------------------------------- |
670| 11600101 | Failed to execute the function.                                 |
671| 11600104 | Discovery invalid.                                              |
672
673**Example**
674
675  ```ts
676  import { BusinessError } from '@ohos.base'
677
678  interface Filters {
679    type: string,
680    value: number
681  }
682
683  interface FilterOptions {
684    filter_op: string, // Optional. The default value is OR.
685    filters: Filters[]
686    }
687
688  interface SubscribeInfo {
689    subscribeId: number,
690    mode: number, // Active discovery
691    medium: number,  // Automatic. Multiple media can be used for device discovery.
692    freq: number,    // High frequency
693    isSameAccount: boolean,
694    isWakeRemote: boolean,
695    capability: number
696  }
697
698  // Automatically generate a unique subscription ID.
699  let subscribeId = Math.floor(Math.random() * 10000 + 1000);
700  let subscribeInfo: SubscribeInfo = {
701    subscribeId: subscribeId,
702    mode: 0xAA, // Active discovery
703    medium: 0,  // Automatic. Multiple media can be used for device discovery.
704    freq: 2,    // High frequency
705    isSameAccount: false,
706    isWakeRemote: false,
707    capability: 1
708  };
709
710  let filters: Filters[] = [
711    {
712        type: "range",
713        value: 50 // Filter discovered devices based on the distance (in cm).
714    }
715  ]
716
717  let filterOptions: FilterOptions = {
718    filter_op: "OR", // Optional. The default value is OR.
719    filters: filters
720  };
721  try {
722    dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered.
723  } catch (err) {
724    let e: BusinessError = err as BusinessError;
725    console.error("startDeviceDiscovery errCode:" + e.code + ",errMessage:" + e.message);
726  }
727  ```
728
729### stopDeviceDiscovery
730
731stopDeviceDiscovery(subscribeId: number): void
732
733Stops device discovery.
734
735**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
736
737**System capability**: SystemCapability.DistributedHardware.DeviceManager
738
739**Parameters**
740
741| Name         | Type  | Mandatory  | Description   |
742| ----------- | ------ | ---- | ----- |
743| subscribeId | number | Yes   | Subscription ID.|
744
745**Error codes**
746
747For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
748
749| ID| Error Message                                                       |
750| -------- | --------------------------------------------------------------- |
751| 11600101 | Failed to execute the function.                                 |
752
753**Example**
754
755  ```ts
756  import { BusinessError } from '@ohos.base'
757
758  try {
759    // stopDeviceDiscovery and startDeviceDiscovery must be used in pairs, and the input parameter **subscribeId** passed in them must be the same.
760    let subscribeId = 12345;
761    dmInstance.stopDeviceDiscovery(subscribeId);
762  } catch (err) {
763    let e: BusinessError = err as BusinessError;
764    console.error("stopDeviceDiscovery errCode:" + e.code + ",errMessage:" + e.message);
765  }
766  ```
767
768### publishDeviceDiscovery<sup>9+</sup>
769
770publishDeviceDiscovery(publishInfo: PublishInfo): void
771
772Publishes device information for discovery purposes. The publish process automatically stops when 2 minutes have elapsed.
773
774**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
775
776**System capability**: SystemCapability.DistributedHardware.DeviceManager
777
778**Parameters**
779
780| Name         | Type                       | Mandatory| Description   |
781| ------------- | ------------------------------- | ---- | ----- |
782| publishInfo   | [PublishInfo](#publishinfo)     | Yes  | Device information to publish.|
783
784**Error codes**
785
786For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
787
788| ID| Error Message                                                       |
789| -------- | --------------------------------------------------------------- |
790| 11600101 | Failed to execute the function.                                 |
791| 11600105 | Publish invalid.                                                |
792
793**Example**
794
795  ```ts
796  import { BusinessError } from '@ohos.base'
797
798  interface PublishInfo {
799    publishId: number,
800    mode: number, // Active discovery
801    freq: number,    // High frequency
802    ranging: boolean // Whether the device supports reporting the distance to the discovery initiator.
803  };
804
805  // Automatically generate a unique subscription ID.
806  let publishId = Math.floor(Math.random() * 10000 + 1000);
807  let publishInfo: PublishInfo = {
808    publishId: publishId,
809    mode: 0xAA, // Active discovery
810    freq: 2,    // High frequency
811    ranging: true  // The device supports reporting the distance to the discovery initiator.
812  };
813
814  try {
815    dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published.
816  } catch (err) {
817    let e: BusinessError = err as BusinessError;
818    console.error("publishDeviceDiscovery errCode:" + e.code + ",errMessage:" + e.message);
819  }
820  ```
821
822### unPublishDeviceDiscovery<sup>9+</sup>
823
824unPublishDeviceDiscovery(publishId: number): void
825
826Stops publishing device information.
827
828**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
829
830**System capability**: SystemCapability.DistributedHardware.DeviceManager
831
832**Parameters**
833
834| Name       | Type| Mandatory| Description |
835| ----------- | -------- | ---- | ----- |
836| publishId   | number   | Yes  | Publish ID.|
837
838**Error codes**
839
840For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
841
842| ID| Error Message                                                       |
843| -------- | --------------------------------------------------------------- |
844| 11600101 | Failed to execute the function.                                 |
845
846**Example**
847
848  ```ts
849  import { BusinessError } from '@ohos.base'
850
851  try {
852    // unPublishDeviceDiscovery and publishDeviceDiscovery must be used in pairs, and the input parameter **publishId** passed in them must be the same.
853    let publishId = 12345;
854    dmInstance.unPublishDeviceDiscovery(publishId);
855  } catch (err) {
856    let e: BusinessError = err as BusinessError;
857    console.error("unPublishDeviceDiscovery errCode:" + e.code + ",errMessage:" + e.message);
858  }
859  ```
860
861### authenticateDevice
862
863authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback&lt;{deviceId: string, pinToken ?: number}&gt;): void
864
865Authenticates a device.
866
867**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
868
869**System capability**: SystemCapability.DistributedHardware.DeviceManager
870
871**Parameters**
872
873| Name        | Type                                    | Mandatory  | Description     |
874| ---------- | ---------------------------------------- | ---- | ------- |
875| deviceInfo | [DeviceInfo](#deviceinfo)                | Yes   | Device information.  |
876| authParam  | [AuthParam](#authparam)                  | Yes   | Authentication parameter.  |
877| callback   | AsyncCallback&lt;{deviceId:&nbsp;string,&nbsp;pinToken&nbsp;?:&nbsp;number}&gt; | Yes   | Callback invoked to return the authentication result.|
878
879**Example**
880
881  ```ts
882  import { BusinessError } from '@ohos.base'
883
884  class Data {
885    deviceId: string = ""
886    pinToken?: number = 0
887  }
888
889  interface DeviceInfo {
890    deviceId: string,
891    deviceName: string
892    deviceType: number,
893    networkId: string,
894    range: number
895  };
896
897  interface ExtraInfo {
898    targetPkgName: string,
899    appName: string,
900    appDescription: string,
901    business: string
902  }
903
904  interface AuthParam {
905    authType: number,//Authentication type. The value 1 means no account PIN authentication.
906    extraInfo: ExtraInfo
907  }
908
909  // Information about the device to authenticate. The information can be obtained from the device discovery result.
910  let deviceInfo: DeviceInfo = {
911    deviceId: "XXXXXXXX",
912    deviceName: "",
913    deviceType: 0x0E,
914    networkId: "xxxxxxx",
915    range: 0
916  };
917  let extraInfo: ExtraInfo = {
918    targetPkgName: 'ohos.samples.xxx',
919    appName: 'xxx',
920    appDescription: 'xxx',
921    business: '0'
922  }
923  let authParam: AuthParam = {
924    authType: 1,// Authentication type. The value 1 means no account PIN authentication.
925    extraInfo: extraInfo
926  }
927
928  try {
929    dmInstance.authenticateDevice(deviceInfo, authParam, (err: BusinessError, data: Data) => {
930      if (err) {
931          console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message);
932          return;
933      }
934      console.info("authenticateDevice result:" + JSON.stringify(data));
935      let token = data.pinToken;
936    });
937  } catch (err) {
938    let e: BusinessError = err as BusinessError;
939    console.error("authenticateDevice errCode:" + e.code + ",errMessage:" + e.message);
940  }
941  ```
942
943### unAuthenticateDevice<sup>8+</sup>
944
945unAuthenticateDevice(deviceInfo: DeviceInfo): void
946
947Deauthenticates a device.
948
949**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
950
951**System capability**: SystemCapability.DistributedHardware.DeviceManager
952
953**Parameters**
954
955| Name        | Type                     | Mandatory  | Description   |
956| ---------- | ------------------------- | ---- | ----- |
957| deviceInfo | [DeviceInfo](#deviceinfo) | Yes   | Device information.|
958
959**Error codes**
960
961For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
962
963| ID| Error Message                                                       |
964| -------- | --------------------------------------------------------------- |
965| 11600101 | Failed to execute the function.                                 |
966
967**Example**
968
969  ```ts
970  import { BusinessError } from '@ohos.base'
971
972  interface DeviceInfo {
973    deviceId: string,
974    deviceName: string,
975    deviceType: number,
976    networkId: string,
977    range: number
978  }
979
980  try {
981    let deviceInfo: DeviceInfo = {
982      deviceId: "XXXXXXXX",
983      deviceName: "",
984      deviceType: 0x0E,
985      networkId: "xxxxxxx",
986      range: 0
987    };
988    dmInstance.unAuthenticateDevice(deviceInfo);
989  } catch (err) {
990    let e: BusinessError = err as BusinessError;
991    console.error("unAuthenticateDevice errCode:" + e.code + ",errMessage:" + e.message);
992  }
993  ```
994
995### verifyAuthInfo
996
997verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback&lt;{deviceId: string, level: number}&gt;): void
998
999Verifies authentication information.
1000
1001**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1002
1003**System capability**: SystemCapability.DistributedHardware.DeviceManager
1004
1005**Parameters**
1006
1007| Name      | Type                                    | Mandatory  | Description     |
1008| -------- | ---------------------------------------- | ---- | ------- |
1009| authInfo | [AuthInfo](#authinfo)                    | Yes   | Authentication information.  |
1010| callback | AsyncCallback&lt;{deviceId:&nbsp;string,&nbsp;level:&nbsp;number}&gt; | Yes   | Callback invoked to return the verification result.|
1011
1012**Example**
1013
1014  ```ts
1015  import { BusinessError } from '@ohos.base'
1016
1017  interface ExtraInfo {
1018    authType: number,
1019    token: number
1020  }
1021
1022  interface AuthInfo {
1023    authType: number,
1024    token: number,
1025    extraInfo: ExtraInfo
1026  }
1027
1028  class Data {
1029    deviceId: string = ""
1030    level: number = 0
1031  }
1032
1033  let extraInfo: ExtraInfo = {
1034    authType: 0,
1035    token: 0
1036  }
1037
1038  let authInfo: AuthInfo = {
1039    authType: 1,
1040    token: 123456,
1041    extraInfo: extraInfo
1042  }
1043  try {
1044    dmInstance.verifyAuthInfo(authInfo, (err: BusinessError, data: Data) => {
1045      if (err) {
1046          console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message);
1047          return;
1048    }
1049    console.info("verifyAuthInfo result:" + JSON.stringify(data));
1050    });
1051  } catch (err) {
1052    let e: BusinessError = err as BusinessError;
1053    console.error("verifyAuthInfo errCode:" + e.code + ",errMessage:" + e.message);
1054  }
1055  ```
1056
1057### setUserOperation<sup>9+</sup>
1058
1059setUserOperation(operateAction: number, params: string): void;
1060
1061Sets a user operation.
1062
1063**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1064
1065**System capability**: SystemCapability.DistributedHardware.DeviceManager
1066
1067**Parameters**
1068
1069| Name      | Type           | Mandatory | Description               |
1070| ------------- | --------------- | ---- | ------------------- |
1071| operateAction | number          | Yes   | User operation.      |
1072| params        | string          | Yes   | Input parameters of the user.|
1073
1074**Example**
1075
1076  ```ts
1077  import { BusinessError } from '@ohos.base'
1078
1079 try {
1080    /*
1081      operateAction = 0 - Grant the permission.
1082      operateAction = 1 - Revoke the permission.
1083      operateAction = 2 - The user operation in the permission request dialog box times out.
1084      operateAction = 3 - Cancel the display of the PIN box.
1085      operateAction = 4 - Cancel the display of the PIN input box.
1086      operateAction = 5 - Confirm the input in the PIN input box.
1087    */
1088    let operation = 0;
1089    dmInstance.setUserOperation(operation, "extra")
1090    } catch (err) {
1091      let e: BusinessError = err as BusinessError;
1092      console.error("setUserOperation errCode:" + e.code + ",errMessage:" + e.message);
1093  }
1094  ```
1095
1096### requestCredentialRegisterInfo<sup>10+</sup>
1097
1098requestCredentialRegisterInfo(requestInfo: string, callback: AsyncCallback<{registerInfo: string}>): void;
1099
1100Obtains the registration information of the credential.
1101
1102**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1103
1104**System capability**: SystemCapability.DistributedHardware.DeviceManager
1105
1106**Parameters**
1107
1108| Name      | Type           | Mandatory | Description               |
1109| ------------- | --------------- | ---- | ------------------- |
1110| requestInfo   | string          | Yes   | Request credential information.      |
1111| callback      | AsyncCallback<{registerInfo: string}>         | Yes   | Callback invoked to return the credential registration information.|
1112
1113**Example**
1114
1115  ```ts
1116  import { BusinessError } from '@ohos.base'
1117
1118  interface CredentialInfo {
1119    version: string,
1120    userId: string
1121  }
1122
1123  class Data {
1124    registerInfo: string = ""
1125  }
1126
1127  let credentialInfo: CredentialInfo = {
1128    version: "1.2.3",
1129    userId: "123"
1130  }
1131
1132  try {
1133    dmInstance.requestCredentialRegisterInfo(credentialInfo, (data: Data) => {
1134      if (data) {
1135          console.info("requestCredentialRegisterInfo result:" + JSON.stringify(data));
1136      } else {
1137          console.info("requestCredentialRegisterInfo result: data is null");
1138      }
1139    });
1140  } catch (err) {
1141    let e: BusinessError = err as BusinessError;
1142    console.error("requestCredentialRegisterInfo err:" + e.code + "," + e.message);
1143  }
1144  ```
1145
1146### importCredential<sup>10+</sup>
1147
1148importCredential(credentialInfo: string, callback: AsyncCallback<{resultInfo: string}>): void;
1149
1150Imports credential information.
1151
1152**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1153
1154**System capability**: SystemCapability.DistributedHardware.DeviceManager
1155
1156**Parameters**
1157
1158| Name      | Type           | Mandatory | Description               |
1159| ------------- | --------------- | ---- | ------------------- |
1160| credentialInfo| string          | Yes   | Credential information to import.      |
1161| callback      | AsyncCallback<{resultInfo: string}>           | Yes   | Callback invoked to return the result.|
1162
1163**Example**
1164
1165  ```ts
1166  import { BusinessError } from '@ohos.base'
1167
1168  class Data {
1169    resultInfo: string = ""
1170  }
1171
1172  interface CredentialData {
1173    credentialType: number,
1174    credentialId: string,
1175    serverPk: string,
1176    pkInfoSignature : string,
1177    pkInfo: string,
1178    authCode: string,
1179    peerDeviceId: string
1180  }
1181
1182  interface CredentialInfo {
1183    processType: number,
1184    authType: number,
1185    userId: string,
1186    deviceId: string,
1187    version: string,
1188    devicePk : string,
1189    credentialData : CredentialData
1190  }
1191
1192  let credentialData: CredentialData = {
1193    credentialType: 2,
1194    credentialId: "102",
1195    serverPk: "3059301306072A8648CE3D020106082A8648CE3D03",
1196    pkInfoSignature : "30440220490BCB4F822004C9A76AB8D97F80041FC0E",
1197    pkInfo: "",
1198    authCode: "",
1199    peerDeviceId: ""
1200  }
1201
1202
1203  let credentialInfo: CredentialInfo = {
1204    processType: 1,
1205    authType: 1,
1206    userId: "123",
1207    deviceId: "aaa",
1208    version: "1.2.3",
1209    devicePk : "0000",
1210    credentialData : credentialData
1211  }
1212
1213  try {
1214    dmInstance.importCredential(credentialInfo, (data: Data) => {
1215      if (data) {
1216          console.info("importCredential result:" + JSON.stringify(data));
1217      } else {
1218          console.info("importCredential result: data is null");
1219      }
1220    });
1221  } catch (err) {
1222    let e: BusinessError = err as BusinessError;
1223    console.error("importCredential err:" + e.code + "," + e.message);
1224  }
1225  ```
1226
1227### deleteCredential<sup>10+</sup>
1228
1229deleteCredential(queryInfo: string, callback: AsyncCallback<{resultInfo: string}>): void;
1230
1231Deletes credential information.
1232
1233**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1234
1235**System capability**: SystemCapability.DistributedHardware.DeviceManager
1236
1237**Parameters**
1238
1239| Name      | Type           | Mandatory | Description               |
1240| ------------- | --------------- | ---- | ------------------- |
1241| queryInfo     | string          | Yes   | Credential information to delete.      |
1242| callback      | AsyncCallback<{resultInfo: string}>           | Yes   | Callback invoked to return the result.|
1243
1244**Example**
1245
1246  ```ts
1247  import { BusinessError } from '@ohos.base'
1248
1249  class Data {
1250    resultInfo: string = ""
1251  }
1252
1253  interface QueryInfo {
1254    processType: number,
1255    authType: number,
1256    userId: string
1257  }
1258
1259  let queryInfo: QueryInfo = {
1260    processType: 1,
1261    authType: 1,
1262    userId: "123"
1263  }
1264
1265  try {
1266    dmInstance.deleteCredential(queryInfo, (data: Data) => {
1267      if (data) {
1268          console.info("deleteCredential result:" + JSON.stringify(data));
1269      } else {
1270          console.info("deleteCredential result: data is null");
1271      }
1272    });
1273  } catch (err) {
1274    let e: BusinessError = err as BusinessError;
1275    console.error("deleteCredential err:" + e.code + "," + e.message);
1276  }
1277  ```
1278
1279### on('uiStateChange')<sup>9+</sup>
1280
1281on(type: 'uiStateChange', callback: Callback&lt;{ param: string}&gt;): void;
1282
1283Subscribes to UI status changes.
1284
1285**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1286
1287**System capability**: SystemCapability.DistributedHardware.DeviceManager
1288
1289**Parameters**
1290
1291| Name     | Type                            | Mandatory| Description                           |
1292| -------- | ------------------------------------ | ---- | ------------------------------ |
1293| type     | string                                | Yes | Event type. The value **'uiStateChange'** indicates UI status changes. |
1294| callback | Callback&lt;{&nbsp;param:&nbsp;string}&gt; | Yes | Callback invoked to return the UI status.       |
1295
1296**Example**
1297
1298  ```ts
1299  import { BusinessError } from '@ohos.base'
1300
1301  class Data {
1302    param: string = ""
1303  }
1304
1305  interface TmpStr {
1306    verifyFailed: boolean
1307  }
1308
1309  try {
1310    dmInstance.on('uiStateChange', (data: Data) => {
1311    console.log("uiStateChange executed, dialog closed" + JSON.stringify(data))
1312    let tmpStr: TmpStr = JSON.parse(data.param)
1313    let isShow = tmpStr.verifyFailed
1314    console.log("uiStateChange executed, dialog closed" + isShow)
1315  });
1316  } catch (err) {
1317    let e: BusinessError = err as BusinessError;
1318    console.error("uiStateChange errCode:" + e.code + ",errMessage:" + e.message);
1319  }
1320  ```
1321
1322### off('uiStateChange')<sup>9+</sup>
1323
1324off(type: 'uiStateChange', callback?: Callback&lt;{ param: string}&gt;): void;
1325
1326Unsubscribes from UI status changes.
1327
1328**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1329
1330**System capability**: SystemCapability.DistributedHardware.DeviceManager
1331
1332**Parameters**
1333
1334| Name     | Type                             | Mandatory| Description                           |
1335| -------- | ------------------------------------- | ---- | ------------------------------ |
1336| type     | string                                | Yes  | Event type. The value **'uiStateChange'** indicates UI status changes. |
1337| callback | Callback&lt;{&nbsp;param:&nbsp;string}&gt; | No  | Callback for the UI status change. |
1338
1339**Example**
1340
1341  ```ts
1342  import { BusinessError } from '@ohos.base'
1343
1344  try {
1345    dmInstance.off('uiStateChange');
1346  } catch (err) {
1347    let e: BusinessError = err as BusinessError;
1348    console.error("uiStateChange errCode:" + e.code + ",errMessage:" + e.message);
1349  }
1350  ```
1351
1352### on('deviceStateChange')
1353
1354on(type: 'deviceStateChange',  callback: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void
1355
1356Subscribes to device state changes.
1357
1358**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1359
1360**System capability**: SystemCapability.DistributedHardware.DeviceManager
1361
1362**Parameters**
1363
1364| Name      | Type                                    | Mandatory  | Description                            |
1365| -------- | ---------------------------------------- | ---- | ------------------------------ |
1366| type     | string                                   | Yes   | Event type. The value **'deviceStateChange'** indicates device state changes. |
1367| callback | Callback&lt;{&nbsp;action:&nbsp;[DeviceStateChangeAction](#devicestatechangeaction),&nbsp;device:&nbsp;[DeviceInfo](#deviceinfo)&nbsp;}&gt; | Yes   | Callback invoked to return the device information and state.     |
1368
1369**Example**
1370
1371  ```ts
1372  import deviceManager from '@ohos.distributedHardware.deviceManager';
1373  import { BusinessError } from '@ohos.base'
1374
1375  class Data {
1376    action: deviceManager.DeviceStateChangeAction = 0
1377    device: deviceManager.DeviceInfo = {
1378      deviceId: "",
1379      deviceName: "",
1380      deviceType: 0,
1381      networkId: "",
1382      range: 0,
1383      authForm:0,
1384    }
1385  }
1386
1387  try {
1388    dmInstance.on('deviceStateChange', (data: Data) => {
1389      console.info("deviceStateChange on:" + JSON.stringify(data));
1390    });
1391  } catch (err) {
1392    let e: BusinessError = err as BusinessError;
1393    console.error("deviceStateChange errCode:" + e.code + ",errMessage:" + e.message);
1394  }
1395  ```
1396
1397### off('deviceStateChange')
1398
1399off(type: 'deviceStateChange', callback?: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void
1400
1401Unsubscribes from device state changes.
1402
1403**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1404
1405**System capability**: SystemCapability.DistributedHardware.DeviceManager
1406
1407**Parameters**
1408
1409| Name      | Type                                    | Mandatory  | Description                         |
1410| -------- | ---------------------------------------- | ---- | --------------------------- |
1411| type     | string                                   | Yes   | Event type. The value **'deviceStateChange'** indicates device state changes.      |
1412| callback | Callback&lt;{&nbsp;action:&nbsp;[DeviceStateChangeAction](#devicestatechangeaction),&nbsp;device:&nbsp;[DeviceInfo](#deviceinfo)&nbsp;}&gt; | No   | Callback for the device state change. |
1413
1414**Example**
1415
1416  ```ts
1417  import deviceManager from '@ohos.distributedHardware.deviceManager';
1418  import { BusinessError } from '@ohos.base'
1419
1420  class Data {
1421    action: deviceManager.DeviceStateChangeAction = 0
1422    device: deviceManager.DeviceInfo = {
1423      deviceId: "",
1424      deviceName: "",
1425      deviceType: 0,
1426      networkId: "",
1427      range: 0,
1428      authForm:0,
1429    }
1430  }
1431
1432  try {
1433    dmInstance.off('deviceStateChange', (data: Data) => {
1434      console.info('deviceStateChange' + JSON.stringify(data));
1435    });
1436  } catch (err) {
1437    let e: BusinessError = err as BusinessError;
1438    console.error("deviceStateChange errCode:" + e.code + ",errMessage:" + e.message);
1439  }
1440  ```
1441
1442### on('deviceFound')
1443
1444on(type: 'deviceFound', callback: Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt;): void
1445
1446Subscribes to device discovery events.
1447
1448**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1449
1450**System capability**: SystemCapability.DistributedHardware.DeviceManager
1451
1452**Parameters**
1453
1454| Name      | Type                                    | Mandatory  | Description                        |
1455| -------- | ---------------------------------------- | ---- | -------------------------- |
1456| type     | string                                   | Yes   | Event type. The value **'deviceFound'** indicates discovery of a device. |
1457| callback | Callback&lt;{&nbsp;subscribeId:&nbsp;number,&nbsp;device:&nbsp;[DeviceInfo](#deviceinfo)&nbsp;}&gt; | Yes   | Callback invoked to return the discovery of a device. |
1458
1459**Example**
1460
1461  ```ts
1462  import deviceManager from '@ohos.distributedHardware.deviceManager';
1463  import { BusinessError } from '@ohos.base'
1464
1465  class Data {
1466    subscribeId: number = 0
1467    device: deviceManager.DeviceInfo = {}
1468  }
1469
1470  try {
1471    dmInstance.on('deviceFound', (data: Data) => {
1472      console.info("deviceFound:" + JSON.stringify(data));
1473    });
1474  } catch (err) {
1475    let e: BusinessError = err as BusinessError;
1476    console.error("deviceFound errCode:" + e.code + ",errMessage:" + e.message);
1477  }
1478  ```
1479
1480### off('deviceFound')
1481
1482off(type: 'deviceFound', callback?: Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt;): void
1483
1484Unsubscribes from device discovery events.
1485
1486**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1487
1488**System capability**: SystemCapability.DistributedHardware.DeviceManager
1489
1490**Parameters**
1491
1492| Name      | Type                                    | Mandatory  | Description                         |
1493| -------- | ---------------------------------------- | ---- | --------------------------- |
1494| type     | string                                   | Yes   | Event type. The value **'deviceFound'** indicates discovery of a device. |
1495| callback | Callback&lt;{&nbsp;subscribeId:&nbsp;number,&nbsp;device:&nbsp;[DeviceInfo](#deviceinfo)&nbsp;}&gt; | No   | Callback for the device discovery event. |
1496
1497**Example**
1498
1499  ```ts
1500  import deviceManager from '@ohos.distributedHardware.deviceManager';
1501  import { BusinessError } from '@ohos.base'
1502
1503  class Data {
1504    subscribeId: number = 0
1505    device: deviceManager.DeviceInfo = {
1506      deviceId: "",
1507      deviceName: "",
1508      deviceType: 0,
1509      networkId: "",
1510      range: 0,
1511      authForm:0,
1512    }
1513  }
1514
1515  try {
1516    dmInstance.off('deviceFound', (data: Data) => {
1517      console.info('deviceFound' + JSON.stringify(data));
1518    });
1519  } catch (err) {
1520    let e: BusinessError = err as BusinessError;
1521    console.error("deviceFound errCode:" + e.code + ",errMessage:" + e.message);
1522  }
1523  ```
1524
1525### on('discoverFail')
1526
1527on(type: 'discoverFail', callback: Callback&lt;{ subscribeId: number, reason: number }&gt;): void
1528
1529Subscribes to device discovery failures.
1530
1531**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1532
1533**System capability**: SystemCapability.DistributedHardware.DeviceManager
1534
1535**Parameters**
1536
1537| Name      | Type                                    | Mandatory  | Description                            |
1538| -------- | ---------------------------------------- | ---- | ------------------------------ |
1539| type     | string                                   | Yes   | Event type. The value **'discoverFail'** indicates a failure in discovering devices. |
1540| callback | Callback&lt;{&nbsp;subscribeId:&nbsp;number,&nbsp;reason:&nbsp;number&nbsp;}&gt; | Yes   | Callback invoked to report a device discovery failure. |
1541
1542**Example**
1543
1544  ```ts
1545  import { BusinessError } from '@ohos.base'
1546
1547  class Data {
1548    subscribeId: number = 0
1549    reason: number = 0
1550  }
1551
1552  try {
1553    dmInstance.on('discoverFail', (data: Data) => {
1554        console.info("discoverFail on:" + JSON.stringify(data));
1555    });
1556  } catch (err) {
1557    let e: BusinessError = err as BusinessError;
1558    console.error("discoverFail errCode:" + e.code + ",errMessage:" + e.message);
1559  }
1560  ```
1561
1562### off('discoverFail')
1563
1564off(type: 'discoverFail', callback?: Callback&lt;{ subscribeId: number, reason: number }&gt;): void
1565
1566Unsubscribes from device discovery failures.
1567
1568**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1569
1570**System capability**: SystemCapability.DistributedHardware.DeviceManager
1571
1572**Parameters**
1573
1574| Name      | Type                                    | Mandatory  | Description               |
1575| -------- | ---------------------------------------- | ---- | ----------------- |
1576| type     | string                                   | Yes   | Event type. The value **'discoverFail'** indicates a failure in discovering devices. |
1577| callback | Callback&lt;{&nbsp;subscribeId:&nbsp;number,&nbsp;reason:&nbsp;number&nbsp;}&gt; | No   | Callback for the device discovery failure. |
1578
1579**Example**
1580
1581  ```ts
1582  import { BusinessError } from '@ohos.base'
1583
1584  class Data {
1585    subscribeId: number = 0
1586    reason: number = 0
1587  }
1588
1589  try {
1590    dmInstance.off('discoverFail', (data: Data) => {
1591      console.info('discoverFail' + JSON.stringify(data));
1592    });
1593  } catch (err) {
1594    let e: BusinessError = err as BusinessError;
1595    console.error("discoverFail errCode:" + e.code + ",errMessage:" + e.message);
1596  }
1597  ```
1598
1599### on('publishSuccess')<sup>9+</sup>
1600
1601on(type: 'publishSuccess', callback: Callback&lt;{ publishId: number }&gt;): void
1602
1603Subscribes to device information publication success events.
1604
1605**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1606
1607**System capability**: SystemCapability.DistributedHardware.DeviceManager
1608
1609**Parameters**
1610
1611| Name    | Type                                | Mandatory| Description                      |
1612| -------- | ---------------------------------------- | ---- | -------------------------- |
1613| type     | string                                   | Yes  | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.|
1614| callback | Callback&lt;{&nbsp;publishId:&nbsp;number&nbsp;}&gt;    | Yes  | Callback invoked to return the publish ID.              |
1615
1616
1617**Example**
1618
1619  ```ts
1620  import { BusinessError } from '@ohos.base'
1621
1622  class Data {
1623    publishId: number = 0
1624  }
1625
1626  try {
1627    dmInstance.on('publishSuccess', (data: Data) => {
1628      console.info("publishSuccess:" + JSON.stringify(data));
1629    });
1630  } catch (err) {
1631    let e: BusinessError = err as BusinessError;
1632    console.error("publishSuccess errCode:" + e.code + ",errMessage:" + e.message);
1633  }
1634  ```
1635
1636### off('publishSuccess')<sup>9+</sup>
1637
1638off(type: 'publishSuccess', callback?: Callback&lt;{ publishId: number }&gt;): void
1639
1640Unsubscribes from device information publication success events.
1641
1642**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1643
1644**System capability**: SystemCapability.DistributedHardware.DeviceManager
1645
1646**Parameters**
1647
1648| Name    | Type                                | Mandatory| Description                         |
1649| -------- | ---------------------------------------- | ---- | --------------------------- |
1650| type     | string                                   | Yes  | Event type. The value **'publishSuccess'** indicates an event of the success in publishing device information. |
1651| callback | Callback&lt;{&nbsp;publishId:&nbsp;number&nbsp;}&gt;    | No  | Callback for the device information publication success event. |
1652
1653**Example**
1654
1655  ```ts
1656  import { BusinessError } from '@ohos.base'
1657
1658  class Data {
1659    publishId: number = 0
1660  }
1661
1662  try {
1663    dmInstance.off('publishSuccess', (data: Data) => {
1664      console.info('publishSuccess' + JSON.stringify(data));
1665    });
1666  } catch (err) {
1667    let e: BusinessError = err as BusinessError;
1668    console.error("publishSuccess errCode:" + e.code + ",errMessage:" + e.message);
1669  }
1670  ```
1671
1672### on('publishFail')<sup>9+</sup>
1673
1674on(type: 'publishFail', callback: Callback&lt;{ publishId: number, reason: number }&gt;): void
1675
1676Subscribes to device information publication failures.
1677
1678**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1679
1680**System capability**: SystemCapability.DistributedHardware.DeviceManager
1681
1682**Parameters**
1683
1684| Name    | Type                                             | Mandatory| Description                            |
1685| -------- | ----------------------------------------------------- | ---- | ------------------------------ |
1686| type     | string                                                | Yes  | Event type. The value **'publishFail'** indicates an event reported when publishing device information fails. |
1687| callback | Callback&lt;{&nbsp;publishId:&nbsp;number,&nbsp;reason:&nbsp;number&nbsp;}&gt; | Yes  | Callback invoked to report a publication failure. |
1688
1689**Example**
1690
1691  ```ts
1692  import { BusinessError } from '@ohos.base'
1693
1694  class Data {
1695    publishId: number = 0
1696    reason: number = 0
1697  }
1698
1699  try {
1700    dmInstance.on('publishFail', (data: Data) => {
1701      console.info("publishFail on:" + JSON.stringify(data));
1702    });
1703  } catch (err) {
1704    let e: BusinessError = err as BusinessError;
1705    console.error("publishFail errCode:" + e.code + ",errMessage:" + e.message);
1706  }
1707  ```
1708
1709### off('publishFail')<sup>9+</sup>
1710
1711off(type: 'publishFail', callback?: Callback&lt;{ publishId: number, reason: number }&gt;): void
1712
1713Unsubscribes from device information publication failures.
1714
1715**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1716
1717**System capability**: SystemCapability.DistributedHardware.DeviceManager
1718
1719**Parameters**
1720
1721| Name    | Type                                             | Mandatory| Description               |
1722| -------- | ----------------------------------------------------- | ---- | ----------------- |
1723| type     | string                                                | Yes  | Event type. The value **'publishFail'** indicates a failure in publishing device information. |
1724| callback | Callback&lt;{&nbsp;publishId:&nbsp;number,&nbsp;reason:&nbsp;number&nbsp;}&gt; | No  | Callback for the device information publication failure. |
1725
1726**Example**
1727
1728  ```ts
1729  import { BusinessError } from '@ohos.base'
1730
1731  class Data {
1732    publishId: number = 0
1733    reason: number = 0
1734  }
1735
1736  try {
1737    dmInstance.off('publishFail', (data: Data) => {
1738      console.info('publishFail' + JSON.stringify(data));
1739    });
1740  } catch (err) {
1741    let e: BusinessError = err as BusinessError;
1742    console.error("publishFail errCode:" + e.code + ",errMessage:" + e.message);
1743  }
1744  ```
1745
1746### on('serviceDie')
1747
1748on(type: 'serviceDie', callback: () =&gt; void): void
1749
1750Subscribes to dead events of the **DeviceManager** service.
1751
1752**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1753
1754**System capability**: SystemCapability.DistributedHardware.DeviceManager
1755
1756**Parameters**
1757
1758| Name      | Type                   | Mandatory  | Description                                      |
1759| -------- | ----------------------- | ---- | ---------------------------------------- |
1760| type     | string                  | Yes   | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
1761| callback | ()&nbsp;=&gt;&nbsp;void | Yes   | Callback invoked when a dead event of the **DeviceManager** service occurs.                      |
1762
1763**Example**
1764
1765  ```ts
1766  import { BusinessError } from '@ohos.base'
1767
1768  try {
1769    dmInstance.on("serviceDie", () => {
1770      console.info("serviceDie on");
1771    });
1772  } catch (err) {
1773    let e: BusinessError = err as BusinessError;
1774    console.error("serviceDie errCode:" + e.code + ",errMessage:" + e.message);
1775  }
1776  ```
1777
1778### off('serviceDie')
1779
1780off(type: 'serviceDie', callback?: () =&gt; void): void
1781
1782Unsubscribes from dead events of the **DeviceManager** service.
1783
1784**Required permissions**: ohos.permission.ACCESS_SERVICE_DM
1785
1786**System capability**: SystemCapability.DistributedHardware.DeviceManager
1787
1788**Parameters**
1789
1790| Name      | Type                   | Mandatory  | Description                                      |
1791| -------- | ----------------------- | ---- | ---------------------------------------- |
1792| type     | string                  | Yes   | Event type. The value **'serviceDie'** indicates a dead event of the **DeviceManager** service. |
1793| callback | ()&nbsp;=&gt;&nbsp;void | No   | Callback for the dead event of the **DeviceManager** service.                  |
1794
1795**Example**
1796
1797  ```ts
1798  import { BusinessError } from '@ohos.base'
1799
1800  try {
1801    dmInstance.off("serviceDie", () => {
1802      console.info("serviceDie off");
1803    });
1804  } catch (err) {
1805    let e: BusinessError = err as BusinessError;
1806    console.error("serviceDie errCode:" + e.code + ",errMessage:" + e.message);
1807  }
1808  ```
1809