openharmony 鸿蒙 js-apis-privacyManager-sys

2025-06-12 浏览 (1)

@ohos.privacyManager (Privacy Management) (System API)

The privacyManager module provides APIs for privacy management, such as management of permission usage records.

NOTE

  • The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
  • The APIs provided by this module are system APIs.

Modules to Import

import { privacyManager } from '@kit.AbilityKit';

privacyManager.addPermissionUsedRecord

addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number, options?: AddPermissionUsedRecordOptions): Promise<void>

Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. The permission usage record includes the application identity (token ID) of the caller, name of the permission used, and number of successful and failed accesses to the target application.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesName of the permission.
successCountnumberYesNumber of successful accesses.
failCountnumberYesNumber of failed accesses.
options12+AddPermissionUsedRecordOptionsNoOptions for adding a permission usage record. This parameter is supported since API version 12.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, the count value is invalid, or usedType in AddPermissionUsedRecordOptions is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.READ_AUDIO', 1, 0).then(() => {
  console.log('addPermissionUsedRecord success');
}).catch((err: BusinessError) => {
  console.error(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
});
// with options param
let options: privacyManager.AddPermissionUsedRecordOptions = {
  usedType: privacyManager.PermissionUsedType.PICKER_TYPE
};
privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.READ_AUDIO', 1, 0, options).then(() => {
  console.log('addPermissionUsedRecord success');
}).catch((err: BusinessError) => {
  console.error(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
});

privacyManager.addPermissionUsedRecord

addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number, callback: AsyncCallback<void>): void

Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. The permission usage record includes the application identity (token ID) of the caller, name of the permission used, and number of successful and failed accesses to the target application.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission name. For details, see Application Permissions.
successCountnumberYesNumber of successful accesses.
failCountnumberYesNumber of failed accesses.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.READ_AUDIO', 1, 0, (err: BusinessError, data: void) => {
  if (err) {
    console.error(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
  } else {
    console.log('addPermissionUsedRecord success');
  }
});

privacyManager.getPermissionUsedRecord

getPermissionUsedRecord(request: PermissionUsedRequest): Promise<PermissionUsedResponse>

Obtains historical permission usage records. This API uses a promise to return the result.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
requestPermissionUsedRequestYesRequest for querying permission usage records.

Return value

TypeDescription
Promise<PermissionUsedResponse>Promise used to return the permission usage records.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The value of flag in request is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let request: privacyManager.PermissionUsedRequest = {
    'tokenId': 1,
    'isRemote': false,
    'deviceId': 'device',
    'bundleName': 'bundle',
    'permissionNames': [],
    'beginTime': 0,
    'endTime': 1,
    'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};

privacyManager.getPermissionUsedRecord(request).then((data) => {
  console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
});

privacyManager.getPermissionUsedRecord

getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void

Obtains historical permission usage records. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
requestPermissionUsedRequestYesRequest for querying permission usage records.
callbackAsyncCallback<PermissionUsedResponse>YesCallback used to return the result. If the operation is successful, err is undefined and data is the permission usage record obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The value of flag in request is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let request: privacyManager.PermissionUsedRequest = {
    'tokenId': 1,
    'isRemote': false,
    'deviceId': 'device',
    'bundleName': 'bundle',
    'permissionNames': [],
    'beginTime': 0,
    'endTime': 1,
    'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};

privacyManager.getPermissionUsedRecord(request, (err: BusinessError, data: privacyManager.PermissionUsedResponse) => {
  if (err) {
    console.error(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
  } else {
    console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
  }
});

privacyManager.setPermissionUsedRecordToggleStatus18+

setPermissionUsedRecordToggleStatus(status: boolean): Promise<void>

Sets whether to record the permission usage of this user. This API uses a promise to return the result.

If status is true, addPermissionUsedRecord can be called to add permission usage records. If status is set false, addPermissionUsedRecord does not add permission usage records. Instead, it deletes the historical records of the user.

Required permissions: ohos.permission.PERMISSION_RECORD_TOGGLE (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
statusbooleanYesSetting of the permission usage record switch. The value true means the switch is toggled on; the value false means the opposite.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100007The service is abnormal.
12100009Common inner error.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

privacyManager.setPermissionUsedRecordToggleStatus(true).then(() => {
  console.log('setPermissionUsedRecordToggleStatus success');
}).catch((err: BusinessError) => {
  console.error(`setPermissionUsedRecordToggleStatus fail, err->${JSON.stringify(err)}`);
});

privacyManager.getPermissionUsedRecordToggleStatus18+

getPermissionUsedRecordToggleStatus(): Promise<boolean>

Obtains the settings of the permission usage record switch for this user. This API uses a promise to return the result.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Return value

TypeDescription
Promise<boolean>Promise used to return the switch settings.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
12100007The service is abnormal.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

privacyManager.getPermissionUsedRecordToggleStatus().then((res) => {
  console.log('getPermissionUsedRecordToggleStatus success');
  if (res == true) {
    console.log('get status is TRUE');
  } else {
    console.log('get status is FALSE');
  }
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedRecordToggleStatus fail, err->${JSON.stringify(err)}`);
});

privacyManager.startUsingPermission

startUsingPermission(tokenID: number, permissionName: Permissions): Promise<void>

Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses a promise to return the result.

When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to use. For details, see Application Permissions.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is used repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => {
  console.log('startUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
});

privacyManager.startUsingPermission18+

startUsingPermission(tokenID: number, permissionName: Permissions, pid?: number, usedType?: PermissionUsedType): Promise<void>

Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses a promise to return the result.

When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache.

For a multi-process application, you can specify the process ID (PID) of the application when reporting the permission usage. If no PID is specified, the privacy service responds by application. When the application exits, the privacy service notifies the privacy indicator and clears the cache.

If a PID is specified, the privacy service responds by process. when the process exits, the privacy service notifies the privacy indicator and clears the cache. In this case, the PID must be that of the application corresponding to the token ID.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to use. For details, see Application Permissions.
pidnumberNoPID of the caller. The default value is -1, which indicates that the privacy service does not respond based on the process lifecycle.
usedTypePermissionUsedTypeNoSensitive permission access mode. The default value is NORMAL_TYPE.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is used repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit'

let tokenID: number = rpc.IPCSkeleton.getCallingTokenId(); // accessTokenId can also be obtained by using bundleManager.getBundleInfoForSelfSync.
let pid: number = rpc.IPCSkeleton.getCallingPid();
let usedType: privacyManager.PermissionUsedType = privacyManager.PermissionUsedType.PICKER_TYPE;

// without pid and usedType
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => {
  console.log('startUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
});
// with pid
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid).then(() => {
  console.log('startUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
});
// with usedType
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', -1, usedType).then(() => {
  console.log('startUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
});
// with pid and usedType
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid, usedType).then(() => {
  console.log('startUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
});

privacyManager.startUsingPermission

startUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void

Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses an asynchronous callback to return the result.

When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to use. For details, see Application Permissions.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is used repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', (err: BusinessError, data: void) => {
  if (err) {
    console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`);
  } else {
    console.log('startUsingPermission success');
  }
});

privacyManager.stopUsingPermission

stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<void>

Stops using a permission. This API must be called by a system application, and used with startUsingPermission in pairs. This API uses a promise to return the result.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to stop using. For details, see Application Permissions.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is not used in pair with 'startUsingPermission'.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => {
  console.log('stopUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`);
});

privacyManager.stopUsingPermission18+

stopUsingPermission(tokenID: number, permissionName: Permissions, pid?: number): Promise<void>

Stops using a permission. This API must be called by a system application, and used with startUsingPermission in pairs. This API uses a promise to return the result.

The value of pid must match that used in startUsingPermission.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to stop using. For details, see Application Permissions.
pidnumberNoPID of the application. The value must match that used in startUsingPermission. The default value is -1.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is not used in pair with 'startUsingPermission'.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit'

let tokenID: number = rpc.IPCSkeleton.getCallingTokenId(); // accessTokenId can also be obtained by using bundleManager.getBundleInfoForSelfSync.
let pid: number = rpc.IPCSkeleton.getCallingPid();

// without pid
privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => {
  console.log('stopUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`);
});

// with pid
privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid).then(() => {
  console.log('stopUsingPermission success');
}).catch((err: BusinessError) => {
  console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`);
});

privacyManager.stopUsingPermission

stopUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void

Stops using a permission. This API must be called by a system application, and used with startUsingPermission in pairs. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIDnumberYesToken ID of the caller, which is the value of accessTokenId in ApplicationInfo.
permissionNamePermissionsYesPermission to stop using. For details, see Application Permissions.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid.
12100002The specified tokenID does not exist or refer to an application process.
12100003The specified permission does not exist or is not an user_grant permission.
12100004The API is not used in pair with 'startUsingPermission'.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', (err: BusinessError, data: void) => {
  if (err) {
    console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`);
  } else {
    console.log('stopUsingPermission success');
  }
});

privacyManager.on

on(type: 'activeStateChange', permissionList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void

Subscribes to changes in the permission usage status of the specified permissions.

Multiple callbacks can be registered for the same permissionList.

The same callback cannot be registered for the permissionLists with overlapping values.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is 'activeStateChange', which indicates the permission usage change.
permissionListArray<Permissions>YesList of target permissions. If this parameter is not specified, this API will subscribe to usage changes of all permissions. For details about the permissions, see Application Permissions.
callbackCallback<ActiveChangeResponse>YesCallback used to return the permission usage change.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters.
12100004The API is used repeatedly with the same input.
12100005The registration time has exceeded the limitation.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let permissionList: Array<Permissions> = [];
try {
    privacyManager.on('activeStateChange', permissionList, (data: privacyManager.ActiveChangeResponse) => {
        console.debug('receive permission state change, data:' + JSON.stringify(data));
    });
} catch(err) {
    console.error(`catch err->${JSON.stringify(err)}`);
}

privacyManager.off

off(type: 'activeStateChange', permissionList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void

Unsubscribes from changes in the permission usage of the specified permissions.

If callback is not specified, this API will unregister all callbacks for permissionList.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is 'activeStateChange', which indicates the permission usage change.
permissionListArray<Permissions>YesList of target permissions. The value must be the same as that in on(). If this parameter is not specified, this API will unsubscribe from usage changes for all permissions. For details about the permissions, see Application Permissions.
callbackCallback<ActiveChangeResponse>NoCallback to unregister.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001Invalid parameter. The permissionNames in the list are all invalid, or the list size exceeds 1024 bytes.
12100004The API is not used in pair with 'on'.
12100007The service is abnormal.
12100008Out of memory.

Example

import { privacyManager, Permissions } from '@kit.AbilityKit';

let permissionList: Array<Permissions> = [];
try {
    privacyManager.off('activeStateChange', permissionList);
} catch(err) {
    console.error(`catch err->${JSON.stringify(err)}`);
}

privacyManager.getPermissionUsedTypeInfos12+

getPermissionUsedTypeInfos(tokenId?: number, permissionName?: Permissions): Promise<Array<PermissionUsedTypeInfo>>

Obtains information about how a sensitive permission is used by an application.

Required permissions: ohos.permission.PERMISSION_USED_STATS (available only to system applications)

System capability: SystemCapability.Security.AccessToken

Parameters

NameTypeMandatoryDescription
tokenIdnumberNoID of the application that uses the sensitive permission. If this parameter is left empty, this API obtains the sensitive permission access information of all applications.
permissionNamePermissionsNoName of the sensitive permission used. If this parameter is left blank, this API obtains the access information about all sensitive permissions.

Return value

TypeDescription
Promise<Array<PermissionUsedTypeInfo>>Promise used to return the information obtained.

Error codes

For details about the error codes, see Access Control Error Codes.

IDError Message
201Permission denied. Interface caller does not have permission.
202Not System App. Interface caller is not a system app.
401Parameter error. Possible causes: 1.Incorrect parameter types.
12100001Invalid parameter. PermissionName exceeds 256 characters.
12100002The input tokenId does not exist.
12100003The input permissionName does not exist.

Example

import { privacyManager, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let tokenId: number = 0; // You can use bundleManager.getApplicationInfo to obtain accessTokenId.
let permissionName: Permissions = 'ohos.permission.CAMERA';
// Without any parameter.
privacyManager.getPermissionUsedTypeInfos().then(() => {
  console.log('getPermissionUsedTypeInfos success');
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedTypeInfos fail, err->${JSON.stringify(err)}`);
});
// Pass in tokenId only.
privacyManager.getPermissionUsedTypeInfos(tokenId).then(() => {
  console.log('getPermissionUsedTypeInfos success');
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedTypeInfos fail, err->${JSON.stringify(err)}`);
});
// Pass in permissionName only.
privacyManager.getPermissionUsedTypeInfos(null, permissionName).then(() => {
  console.log('getPermissionUsedTypeInfos success');
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedTypeInfos fail, err->${JSON.stringify(err)}`);
});
// Pass in tokenId and permissionName.
privacyManager.getPermissionUsedTypeInfos(tokenId, permissionName).then(() => {
  console.log('getPermissionUsedTypeInfos success');
}).catch((err: BusinessError) => {
  console.error(`getPermissionUsedTypeInfos fail, err->${JSON.stringify(err)}`);
});

PermissionUsageFlag

Enumerates the modes for querying the permission usage records.

System capability: SystemCapability.Security.AccessToken

NameValueDescription
FLAG_PERMISSION_USAGE_SUMMARY0Query the permission usage summary.
FLAG_PERMISSION_USAGE_DETAIL1Query detailed permission usage records.

PermissionUsedRequest

Represents the request for querying permission usage records.

System capability: SystemCapability.Security.AccessToken

NameTypeMandatoryDescription
tokenIdnumberNoToken ID of the application (caller).
By default, all applications are queried.
isRemotebooleanNoWhether to query the permission usage records of the remote device.
The default value is false, which means the permission usage records of the local device are queried by default.
deviceIdstringNoID of the device hosting the target application.
The default value is the local device ID.
bundleNamestringNoBundle name of the target application.
By default, all applications are queried.
permissionNamesArray<Permissions>NoPermissions to query.
By default, the usage records of all permissions are queried.
beginTimenumberNoStart time of the query, in ms.
The default value is 0, which means the start time is not set.
endTimenumberNoEnd time of the query, in ms.
The default value is 0, which means the end time is not set.
flagPermissionUsageFlagYesQuery mode.

PermissionUsedResponse

Represents the permission usage records of all applications.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
beginTimenumberYesNoStart time of the query, in ms.
endTimenumberYesNoEnd time of the query, in ms.
bundleRecordsArray<BundleUsedRecord>YesNoPermission usage records.

BundleUsedRecord

Represents the permission access records of an application.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
tokenIdnumberYesNoToken ID of the application (caller).
isRemotebooleanYesNoWhether it is a distributed device. The default value is false, which indicates that the device is not a distributed device.
deviceIdstringYesNoID of the device hosting the target application.
bundleNamestringYesNoBundle name of the target application.
permissionRecordsArray<PermissionUsedRecord>YesNoPermission usage records of the target application.

PermissionUsedRecord

Represents the usage records of a permission.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
permissionNamePermissionsYesNoName of the permission.
accessCountnumberYesNoTotal number of times that the permission is accessed.
rejectCountnumberYesNoTotal number of times that the access to the permission is rejected.
lastAccessTimenumberYesNoLast time when the permission was accessed, accurate to ms.
lastRejectTimenumberYesNoLast time when the access to the permission was rejected, accurate to ms.
lastAccessDurationnumberYesNoLast access duration, in ms.
accessRecordsArray<UsedRecordDetail>YesNoSuccessful access records. This parameter is valid only when flag is FLAG_PERMISSION_USAGE_DETAIL. By default, 10 records are provided.
rejectRecordsArray<UsedRecordDetail>YesNoRejected access records. This parameter is valid only when flag is FLAG_PERMISSION_USAGE_DETAIL. By default, 10 records are provided.

UsedRecordDetail

Represents the details of a single access record.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
statusnumberYesNoAccess status.
lockScreenStatus11+numberYesNoStatus of the screen during the access.
- 1: The screen is not locked when the permission is used.
- 2: The screen is locked when the permission is used.
timestampnumberYesNoAccess timestamp, in ms.
accessDurationnumberYesNoAccess duration, in ms.
count11+numberYesNoNumber of successful or failed accesses.
usedType12+PermissionUsedTypeYesNoMeans for using the sensitive permission.

PermissionActiveStatus

Enumerates the permission usage statuses.

System capability: SystemCapability.Security.AccessToken

NameValueDescription
PERM_INACTIVE0The permission is not used.
PERM_ACTIVE_IN_FOREGROUND1The permission is being used by an application running in the foreground.
PERM_ACTIVE_IN_BACKGROUND2The permission is being used by an application running in the background.

ActiveChangeResponse

Defines the detailed permission usage information.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
callingTokenId18+numberYesNoToken ID of the caller. This parameter is invalid when activeStatus is INACTIVE.
tokenIdnumberYesNoToken ID of the application whose permission usage changes are subscribed to.
permissionNamePermissionsYesNoPermissions whose usage status changes.
deviceIdstringYesNoDevice ID.
activeStatusPermissionActiveStatusYesNoPermission usage status.
usedType18+PermissionUsedTypeYesNoSensitive permission access mode. This parameter is invalid when activeStatus is INACTIVE.

PermissionUsedType12+

Enumerates the means for using a sensitive permission.

System capability: SystemCapability.Security.AccessToken

NameValueDescription
NORMAL_TYPE0The sensitive permission is used after authorization through a dialog box or a system settings page.
PICKER_TYPE1The sensitive permission is used through a system picker. This access mode does not grant the permissions to the application.
SECURITY_COMPONENT_TYPE2The sensitive permission is used through a security component, which comes with the authorization.

PermissionUsedTypeInfo12+

Represents detailed information about the use of a permission.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
tokenIdnumberYesNoToken ID of the application that uses the sensitive permission.
permissionNamePermissionsYesNoName of the sensitive permission.
usedTypePermissionUsedTypeYesNoAccess mode of the sensitive permission.

AddPermissionUsedRecordOptions12+

Represents the options for adding a permission usage record.

System capability: SystemCapability.Security.AccessToken

NameTypeReadableWritableDescription
usedTypePermissionUsedTypeYesNoAccess mode of the sensitive permission.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Ability Kit

harmony 鸿蒙AbilityAccessControl

harmony 鸿蒙AbilityBase

harmony 鸿蒙AbilityBase_Element

harmony 鸿蒙AbilityRuntime

harmony 鸿蒙bundle

harmony 鸿蒙OH_NativeBundle_ApplicationInfo

harmony 鸿蒙OH_NativeBundle_ElementName

harmony 鸿蒙ability_access_control.h

harmony 鸿蒙ability_base_common.h

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/BD5O84