1# @ohos.net.statistics (Traffic Management) (System API)
2
3The **statistics** module provides APIs to query real-time or historical traffic statistics by the specified network interface card (NIC) or user ID (UID).
4
5> **NOTE**
6> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
7> This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.net.statistics (Traffic Management)](js-apis-net-statistics.md).
8
9## Modules to Import
10
11```js
12import { statistics } from '@kit.NetworkKit';
13```
14
15
16## statistics.on('netStatsChange')<sup>10+</sup>
17
18on(type: 'netStatsChange', callback: Callback\<NetStatsChangeInfo\>): void
19
20Subscribes to traffic change events.
21
22**System API**: This is a system API.
23
24**Required permissions**: ohos.permission.GET_NETWORK_STATS
25
26**System capability**: SystemCapability.Communication.NetManager.Core
27
28**Parameters**
29
30| Name  | Type                                       | Mandatory| Description                                                              |
31| -------- | ------------------------------------------- | ---- | ----------------------------------------------------------------- |
32| type     | string                                      | Yes  | Event type. This field has a fixed value of **netStatsChange**.                                |
33| callback | Callback\<[NetStatsChangeInfo](#netstatschangeinfo11)\> | Yes  | Callback invoked when the traffic changes.|
34
35**Error codes**
36
37For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
38
39| ID| Error Message                                    |
40| --------- | -------------------------------------------- |
41| 201       | Permission denied.                           |
42| 202       | Non-system applications use system APIs.     |
43| 401       | Parameter error.                             |
44| 2100002   | Failed to connect to the service.            |
45| 2100003   | System internal error.                       |
46
47**Example**
48
49```js
50import { statistics } from '@kit.NetworkKit';
51
52class IFace {
53  iface: string = ""
54  uid?: number = 0
55}
56statistics.on('netStatsChange', (data: IFace) => {
57  console.log('on netStatsChange' + JSON.stringify(data));
58});
59```
60
61## statistics.off('netStatsChange')<sup>10+</sup>
62
63off(type: 'netStatsChange', callback?: Callback\<NetStatsChangeInfo>): void;
64
65Unsubscribes from traffic change events.
66
67**System API**: This is a system API.
68
69**Required permissions**: ohos.permission.GET_NETWORK_STATS
70
71**System capability**: SystemCapability.Communication.NetManager.Core
72
73**Parameters**
74
75| Name  | Type                                       | Mandatory| Description                                                              |
76| -------- | ------------------------------------------- | ---- | ----------------------------------------------------------------- |
77| type     | string                                      | Yes  | Event type. This field has a fixed value of **netStatsChange**.                            |
78| callback | Callback\<[NetStatsChangeInfo](#netstatschangeinfo11)\> | No  | Callback invoked when the traffic changes.|
79
80**Error codes**
81
82For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
83
84| ID| Error Message                                    |
85| --------- | -------------------------------------------- |
86| 201       | Permission denied.                           |
87| 202       | Non-system applications use system APIs.     |
88| 401       | Parameter error.                             |
89| 2100002   | Failed to connect to the service.            |
90| 2100003   | System internal error.                       |
91
92**Example**
93
94```js
95import { statistics } from '@kit.NetworkKit';
96
97class IFace {
98  iface: string = ""
99  uid?: number = 0
100}
101let callback: (data: IFace) => void = (data: IFace) => {
102    console.log("on netStatsChange, iFace:" + data.iface + " uid: " + data.uid);
103}
104statistics.on('netStatsChange', callback);
105// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
106statistics.off('netStatsChange', callback);
107statistics.off('netStatsChange');
108```
109
110## statistics.getTrafficStatsByIface<sup>10+</sup>
111
112getTrafficStatsByIface(ifaceInfo: IfaceInfo, callback: AsyncCallback\<NetStatsInfo>): void;
113
114Obtains the historical traffic statistics of the specified NIC. This API uses an asynchronous callback to return the result.
115
116**System API**: This is a system API.
117
118**Required permissions**: ohos.permission.GET_NETWORK_STATS
119
120**System capability**: SystemCapability.Communication.NetManager.Core
121
122**Parameters**
123
124| Name   | Type                                           | Mandatory| Description                                                                                   |
125| --------- | ----------------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
126| ifaceInfo | [IfaceInfo](#ifaceinfo10)                       | Yes  | NIC information. For details, see [IfaceInfo](#ifaceinfo10).                                    |
127| callback  | AsyncCallback\<[NetStatsInfo](#netstatsinfo10)> | Yes  | Callback used to return the result. If the operation is successful, **error** is **undefined** and **statsInfo** is the historical traffic statistics of the NIC. Otherwise, **error** is an error object.|
128
129**Error codes**
130
131For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
132
133| ID| Error Message                                    |
134| --------- | -------------------------------------------- |
135| 201       | Permission denied.                           |
136| 202       | Non-system applications use system APIs.     |
137| 401       | Parameter error.                             |
138| 2100001   | Invalid parameter value.                     |
139| 2100002   | Failed to connect to the service.            |
140| 2100003   | System internal error.                       |
141| 2103017   | Failed to read the database.                 |
142
143**Example**
144
145```js
146import { BusinessError } from '@kit.BasicServicesKit';
147import { statistics } from '@kit.NetworkKit';
148
149let iFaceInfo: statistics.IfaceInfo | null = null;
150if (iFaceInfo) {
151  statistics.getTrafficStatsByIface(iFaceInfo as statistics.IfaceInfo, (error: BusinessError, statsInfo: statistics.NetStatsInfo) => {
152    console.log(JSON.stringify(error));
153    console.log(
154      "getTrafficStatsByIface bytes of received = " +
155      JSON.stringify(statsInfo.rxBytes)
156    );
157    console.log(
158      "getTrafficStatsByIface bytes of sent = " +
159      JSON.stringify(statsInfo.txBytes)
160    );
161    console.log(
162      "getTrafficStatsByIface packets of received = " +
163      JSON.stringify(statsInfo.rxPackets)
164    );
165    console.log(
166      "getTrafficStatsByIface packets of sent = " +
167      JSON.stringify(statsInfo.txPackets)
168    );
169  });
170}
171```
172
173## statistics.getTrafficStatsByIface<sup>10+</sup>
174
175getTrafficStatsByIface(ifaceInfo: IfaceInfo): Promise\<NetStatsInfo>;
176
177Obtains the historical traffic statistics of the specified NIC. This API uses a promise to return the result.
178
179**System API**: This is a system API.
180
181**Required permissions**: ohos.permission.GET_NETWORK_STATS
182
183**System capability**: SystemCapability.Communication.NetManager.Core
184
185| Name   | Type                     | Mandatory| Description                                               |
186| --------- | ------------------------- | ---- | --------------------------------------------------- |
187| ifaceInfo | [IfaceInfo](#ifaceinfo10) | Yes  | NIC information. For details, see [IfaceInfo](#ifaceinfo10).|
188
189**Return value**
190| Type| Description|
191| -------- | -------- |
192| Promise\<[NetStatsInfo](#netstatsinfo10)> | Promise used to return the result, which is the historical traffic statistics of the specified NIC.|
193
194**Error codes**
195
196For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
197
198| ID| Error Message                                    |
199| --------- | -------------------------------------------- |
200| 201       | Permission denied.                           |
201| 202       | Non-system applications use system APIs.     |
202| 401       | Parameter error.                             |
203| 2100001   | Invalid parameter value.                     |
204| 2100002   | Failed to connect to the service.            |
205| 2100003   | System internal error.                       |
206| 2103017   | Failed to read the database.                 |
207
208**Example**
209
210```js
211import { statistics } from '@kit.NetworkKit';
212
213let iFaceInfo: statistics.IfaceInfo | null = null;
214if (iFaceInfo) {
215  statistics.getTrafficStatsByIface(iFaceInfo as statistics.IfaceInfo).then((statsInfo: statistics.NetStatsInfo) => {
216    console.log(
217      "getTrafficStatsByIface bytes of received = " +
218      JSON.stringify(statsInfo.rxBytes)
219    );
220    console.log(
221      "getTrafficStatsByIface bytes of sent = " +
222      JSON.stringify(statsInfo.txBytes)
223    );
224    console.log(
225      "getTrafficStatsByIface packets of received = " +
226      JSON.stringify(statsInfo.rxPackets)
227    );
228    console.log(
229      "getTrafficStatsByIface packets of sent = " +
230      JSON.stringify(statsInfo.txPackets)
231    );
232  });
233}
234```
235
236## statistics.getTrafficStatsByUid<sup>10+</sup>
237
238getTrafficStatsByUid(uidInfo: UidInfo, callback: AsyncCallback\<NetStatsInfo>): void;
239
240Obtains the historical traffic statistics of the specified application. This API uses an asynchronous callback to return the result.
241
242**System API**: This is a system API.
243
244**Required permissions**: ohos.permission.GET_NETWORK_STATS
245
246**System capability**: SystemCapability.Communication.NetManager.Core
247
248**Parameters**
249
250| Name  | Type                                           | Mandatory| Description                                                                                   |
251| -------- | ----------------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
252| uidInfo  | [UidInfo](#uidinfo10)                           | Yes  | Application information. For details, see [UidInfo](#uidinfo10).                                        |
253| callback | AsyncCallback\<[NetStatsInfo](#netstatsinfo10)> | Yes  | Callback used to return the result. If the operation is successful, **error** is **undefined** and **statsInfo** is the historical traffic statistics of the application. Otherwise, **error** is an error object.|
254
255**Error codes**
256
257For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
258
259| ID| Error Message                                    |
260| --------- | -------------------------------------------- |
261| 201       | Permission denied.                           |
262| 202       | Non-system applications use system APIs.     |
263| 401       | Parameter error.                             |
264| 2100001   | Invalid parameter value.                     |
265| 2100002   | Failed to connect to the service.            |
266| 2100003   | System internal error.                       |
267| 2103017   | Failed to read the database.                 |
268
269**Example**
270
271```js
272import { BusinessError } from '@kit.BasicServicesKit';
273import { statistics } from '@kit.NetworkKit';
274
275let uidInfo: statistics.UidInfo = {
276  uid: 20010037,
277  ifaceInfo: {
278    iface: '',
279    startTime: 1,
280    endTime: 3,
281  }
282}
283
284statistics.getTrafficStatsByUid(
285  uidInfo,
286  (error: BusinessError, statsInfo: statistics.NetStatsInfo) => {
287    console.log(JSON.stringify(error));
288    console.log(
289      "getTrafficStatsByUid bytes of received = " +
290      JSON.stringify(statsInfo.rxBytes)
291    );
292    console.log(
293      "getTrafficStatsByUid bytes of sent = " +
294      JSON.stringify(statsInfo.txBytes)
295    );
296    console.log(
297      "getTrafficStatsByUid packets of received = " +
298      JSON.stringify(statsInfo.rxPackets)
299    );
300    console.log(
301      "getTrafficStatsByUid packets of sent = " +
302      JSON.stringify(statsInfo.txPackets)
303    );
304  }
305);
306```
307
308## statistics.getTrafficStatsByUid<sup>10+</sup>
309
310getTrafficStatsByUid(uidInfo: UidInfo): Promise\<NetStatsInfo>;
311
312Obtains the historical traffic statistics of the specified application. This API uses a promise to return the result.
313
314**System API**: This is a system API.
315
316**Required permissions**: ohos.permission.GET_NETWORK_STATS
317
318**System capability**: SystemCapability.Communication.NetManager.Core
319
320**Parameters**
321
322| Name | Type                 | Mandatory| Description                                           |
323| ------- | --------------------- | ---- | ----------------------------------------------- |
324| uidInfo | [UidInfo](#uidinfo10) | Yes  | Application information. For details, see [UidInfo](#uidinfo10).|
325
326**Return value**
327
328| Type                                     | Description                                              |
329| ----------------------------------------- | -------------------------------------------------- |
330| Promise\<[NetStatsInfo](#netstatsinfo10)> | Promise used to return the result, which is the historical traffic statistics of the specified NIC.|
331
332**Error codes**
333
334For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
335
336| ID| Error Message                                    |
337| --------- | -------------------------------------------- |
338| 201       | Permission denied.                           |
339| 202       | Non-system applications use system APIs.     |
340| 401       | Parameter error.                             |
341| 2100001   | Invalid parameter value.                     |
342| 2100002   | Failed to connect to the service.            |
343| 2100003   | System internal error.                       |
344| 2103017   | Failed to read the database.                 |
345
346**Example**
347
348```js
349import statistics from '@ohos.net.statistics'
350
351let uidInfo: statistics.UidInfo = {
352  uid: 20010037,
353  ifaceInfo: {
354    iface: '',
355    startTime: 1,
356    endTime: 3,
357  }
358}
359
360statistics.getTrafficStatsByUid(uidInfo).then((statsInfo: statistics.NetStatsInfo) => {
361  console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes));
362  console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes));
363  console.log("getTrafficStatsByUid packets of received = " + JSON.stringify(statsInfo.rxPackets));
364  console.log("getTrafficStatsByUid packets of sent = " + JSON.stringify(statsInfo.txPackets));
365})
366```
367
368## statistics.getTrafficStatsByNetwork<sup>12+</sup>
369
370getTrafficStatsByNetwork(networkInfo: NetworkInfo): Promise\<UidNetStatsInfo>
371
372Obtains the traffic statistics of all applications on the specified network within the specified period. This API uses a promise to return the result.
373
374**System API**: This is a system API.
375
376**Required permissions**: ohos.permission.GET_NETWORK_STATS
377
378**System capability**: SystemCapability.Communication.NetManager.Core
379
380**Parameters**
381
382| Name        | Type                           | Mandatory| Description                                        |
383|-------------|-------------------------------|----|--------------------------------------------|
384| networkInfo | [NetworkInfo](#networkinfo12) | Yes | Network information. For details, see [NetworkInfo](#networkinfo12).|
385
386**Return value**
387
388| Type                                             | Description                              |
389|-------------------------------------------------|----------------------------------|
390| Promise\<[UidNetStatsInfo](#uidnetstatsinfo12)> | Promise used to return the result, which is the historical traffic statistics of all applications.|
391
392**Error codes**
393
394For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
395
396| ID| Error Message                                    |
397| --------- | -------------------------------------------- |
398| 201       | Permission denied.                           |
399| 202       | Non-system applications use system APIs.     |
400| 401       | Parameter error.                             |
401| 2100001   | Invalid parameter value.                     |
402| 2100002   | Failed to connect to the service.            |
403| 2100003   | System internal error.                       |
404| 2103017   | Failed to read the database.                 |
405
406**Example**
407
408```js
409import { connection, statistics } from '@kit.NetworkKit';
410
411let networkInfo: statistics.NetworkInfo = {
412  type: connection.NetBearType.BEARER_CELLULAR,
413  startTime: Math.floor(Date.now() / 1000) - 86400 * 7,
414  endTime: Math.floor(Date.now() / 1000) + 5,
415  simId: 1,
416}
417
418statistics.getTrafficStatsByNetwork(networkInfo).then((statsInfo: statistics.UidNetStatsInfo) => {
419  let rank: Map<string, object> = new Map<string, object>(Object.entries(statsInfo));
420  rank.forEach((value: object, key: string) => {
421    console.info("getTrafficStatsByNetwork key=" + key + ", value=" + JSON.stringify(value));
422  })
423})
424```
425
426## statistics.getTrafficStatsByUidNetwork<sup>12+</sup>
427
428getTrafficStatsByUidNetwork(uid: number, networkInfo: NetworkInfo): Promise\<NetStatsInfoSequence>
429
430Obtains the traffic statistics of the specified application on the specified network within the specified period. This API uses a promise to return the result.
431
432**System API**: This is a system API.
433
434**Required permissions**: ohos.permission.GET_NETWORK_STATS
435
436**System capability**: SystemCapability.Communication.NetManager.Core
437
438**Parameters**
439
440| Name        | Type                           | Mandatory| Description                                        |
441|-------------|-------------------------------|----|--------------------------------------------|
442| uid         | number                        | Yes | Application UID.                              |
443| networkInfo | [NetworkInfo](#networkinfo12) | Yes | Network information. For details, see [NetworkInfo](#networkinfo12).|
444
445**Return value**
446
447| Type                                                       | Description                              |
448|-----------------------------------------------------------|----------------------------------|
449| Promise\<[NetStatsInfoSequence](#netstatsinfosequence12)> | Promise used to return the result, which is the historical traffic statistics of the specified application.|
450
451**Error codes**
452
453For details about the error codes, see [Traffic Management Error Codes](errorcode-net-statistics.md).
454
455| ID| Error Message                                    |
456| --------- | -------------------------------------------- |
457| 201       | Permission denied.                           |
458| 202       | Non-system applications use system APIs.     |
459| 401       | Parameter error.                             |
460| 2100001   | Invalid parameter value.                     |
461| 2100002   | Failed to connect to the service.            |
462| 2100003   | System internal error.                       |
463| 2103017   | Failed to read the database.                 |
464
465**Example**
466
467```js
468import { connection, statistics } from '@kit.NetworkKit';
469
470let uid: number = 20020147;
471let networkInfo: statistics.NetworkInfo = {
472  type: connection.NetBearType.BEARER_CELLULAR,
473  startTime: Math.floor(Date.now() / 1000) - 86400 * 7,
474  endTime: Math.floor(Date.now() / 1000) + 5,
475  simId: 1,
476}
477
478statistics.getTrafficStatsByUidNetwork(uid, networkInfo).then((statsInfoSequence: statistics.NetStatsInfoSequence) => {
479  for (let i = 0; i < statsInfoSequence.length; i--) {
480    console.info("getTrafficStatsByUidNetwork item:" + JSON.stringify(statsInfoSequence[i]));
481  }
482})
483```
484
485## IfaceInfo<sup>10+</sup>
486
487Defines the parameters for querying historical traffic of an NIC.
488
489**System API**: This is a system API.
490
491**System capability**: SystemCapability.Communication.NetManager.Core
492
493| Name     | Type  | Mandatory| Description                             |
494| --------- | ------ | ---- | --------------------------------- |
495| iface     | string | Yes  | NIC name.                   |
496| startTime | number | Yes  | Start time of the query, which is a timestamp in seconds.|
497| endTime   | number | Yes  | End time of the query, which is a timestamp in seconds.|
498
499## UidInfo<sup>10+</sup>
500
501Defines the parameters for querying historical traffic of an application.
502
503**System API**: This is a system API.
504
505**System capability**: SystemCapability.Communication.NetManager.Core
506
507| Name     | Type                                 | Mandatory| Description                       |
508| --------- | ------------------------------------- | ---- | -------------------------- |
509| ifaceInfo | IfaceInfo\<[IfaceInfo](#ifaceinfo10)> | Yes  | NIC information, including the NIC name and query time range.|
510| uid       | number                                | Yes  | Application UID.         |
511
512## NetStatsInfo<sup>10+</sup>
513
514Defines the historical traffic information.
515
516**System API**: This is a system API.
517
518**System capability**: SystemCapability.Communication.NetManager.Core
519
520| Name     | Type  | Mandatory| Description                     |
521| --------- | ------ | ---- | ------------------------ |
522| rxBytes   | number | Yes  | Downlink traffic, in bytes.|
523| txBytes   | number | Yes  | Uplink traffic, in bytes.|
524| rxPackets | number | Yes  | Number of downlink packets.         |
525| txPackets | number | Yes  | Number of uplink packets.         |
526
527## NetStatsChangeInfo<sup>11+</sup>
528
529Defines the NIC status and usage of an application.
530
531**System API**: This is a system API.
532
533**System capability**: SystemCapability.Communication.NetManager.Core
534
535| Name     | Type  | Mandatory| Description      |
536| --------- | ------ | ---- | --------- |
537| iface     | string | Yes  | NIC name.|
538| uid       | number | No  | Application UID. |
539
540## NetworkInfo<sup>12+</sup>
541
542Defines the network information.
543
544**System API**: This is a system API.
545
546**System capability**: SystemCapability.Communication.NetManager.Core
547
548| Name       | Type                                                  | Mandatory| Description          |
549|-----------|------------------------------------------------------|----|--------------|
550| type      | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes | Network type.       |
551| startTime | number                                               | Yes | Start timestamp, in seconds.|
552| endTime   | number                                               | Yes | End timestamp, in seconds.|
553| simId     | number                                               | No | SIM card ID.   |
554
555## UidNetStatsInfo<sup>12+</sup>
556
557Defines the historical traffic statistics of all applications.
558
559**System API**: This is a system API.
560
561**System capability**: SystemCapability.Communication.NetManager.Core
562
563| Name       | Type                                           | Mandatory| Description          |
564|-----------|-----------------------------------------------|----|--------------|
565| undefined | [uid:number]: [NetStatsInfo](#netstatsinfo10) | Yes | Historical traffic statistics of all applications.|
566
567## NetStatsInfoSequence<sup>12+</sup>
568
569Defines the historical traffic statistics of the specified application.
570
571**System API**: This is a system API.
572
573**System capability**: SystemCapability.Communication.NetManager.Core
574
575| Name       | Type                             | Mandatory| Description          |
576|-----------|---------------------------------|----|--------------|
577| startTime | number                          | Yes | Start timestamp, in seconds.|
578| endTime   | number                          | Yes | End timestamp, in seconds.|
579| info      | [NetStatsInfo](#netstatsinfo10) | Yes | Historical traffic statistics of the specified application.|
580