harmony 鸿蒙@ohos.privacyManager (Privacy Management)

2022-08-09 浏览 (759)

@ohos.privacyManager (Privacy Management)

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 '@ohos.privacyManager';

privacyManager.addPermissionUsedRecord

addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number): 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 invoker, 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesName of the permission.
successCountnumberYesNumber of successful accesses.
failCountnumberYesNumber of failed accesses.

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
12100001The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, 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.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

let tokenID: number = 0; // You can use getApplicationInfo to obtain accessTokenId.
try {
    privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0).then(() => {
        console.log('addPermissionUsedRecord success');
    }).catch((err: BusinessError) => {
        console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
    });
} catch(err) {
    console.log(`catch 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 invoker, 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesApplication permission name. Valid permission names can be obtained in the Application Permission List.
successCountnumberYesNumber of successful accesses.
failCountnumberYesNumber of failed accesses.
callbackAsyncCallback<void>YesCallback invoked 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
12100001The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256, 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.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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

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
12100001The parameter is invalid. 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.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

let request: privacyManager.PermissionUsedRequest = {
    'tokenId': 1,
    'isRemote': false,
    'deviceId': 'device',
    'bundleName': 'bundle',
    'permissionNames': [],
    'beginTime': 0,
    'endTime': 1,
    'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
    privacyManager.getPermissionUsedRecord(request).then((data) => {
        console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
    }).catch((err: BusinessError) => {
        console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
    });
} catch(err) {
    console.log(`catch 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 invoked 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
12100001The parameter is invalid. 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.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

let request: privacyManager.PermissionUsedRequest = {
    'tokenId': 1,
    'isRemote': false,
    'deviceId': 'device',
    'bundleName': 'bundle',
    'permissionNames': [],
    'beginTime': 0,
    'endTime': 1,
    'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
    privacyManager.getPermissionUsedRecord(request, (err: BusinessError, data: privacyManager.PermissionUsedResponse) => {
        if (err) {
            console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
        } else {
            console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
        }
    });
} catch(err) {
    console.log(`catch err->${JSON.stringify(err)}`);
}

privacyManager.startUsingPermission

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

Starts to use a permission and flushes the permission usage record. This API is called by a system application, either running in the foreground or background, and uses a promise to return the result. 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesName of the permission to use. Valid permission names can be obtained in the Application Permission List.

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
12100001The tokenID is 0, permissionName is longer than 256 bytes, 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 interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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

privacyManager.startUsingPermission

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

Starts to use a permission and flushes the permission usage record. This API is called by a system application, either running in the foreground or background, and uses a promise to return the result. 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesName of the permission to use. Valid permission names can be obtained in the Application Permission List.
callbackAsyncCallback<void>YesCallback invoked 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
12100001The tokenID is 0, permissionName is longer than 256 bytes, 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 interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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

privacyManager.stopUsingPermission

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

Stops using a permission. This API is called by a system application and uses a promise to return the result. startUsingPermission and stopUsingPermission are used 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesName of the permission to use. Valid permission names can be obtained in the Application Permission List.

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
12100001The tokenID is 0, permissionName is longer than 256 bytes, 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 interface is not used with
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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

privacyManager.stopUsingPermission

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

Stops using a permission. This API is called by a system application and uses a promise to return the result. startUsingPermission and stopUsingPermission are used 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
tokenIDnumberYesApplication token ID of the invoker. The value can be obtained from ApplicationInfo.
permissionNamePermissionsYesName of the permission to use. Valid permission names can be obtained in the Application Permission List.
callbackAsyncCallback<void>YesCallback invoked 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
12100001The tokenID is 0, permissionName is longer than 256 bytes, 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 interface is not used with
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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

privacyManager.on

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

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

Multiple callbacks can be registered for the same permissionList.

The same callback cannot be registered for the permissionLists with common 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 the permissions to be observed. If this parameter is left empty, this API subscribes to the permission usage status change of all permissions. Valid permission names can be obtained in the Application Permission List.
callbackCallback<ActiveChangeResponse>YesCallback invoked to return a change in the permission usage.

Error codes

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

IDError Message
12100001The parameter is invalid. The tokenID is 0, or the string size of permissionName is larger than 256.
12100004The interface is called repeatedly with the same input.
12100005The registration time has exceeded the limitation.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager, { Permissions } from '@ohos.privacyManager';
import { BusinessError } from '@ohos.base';

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.log(`catch err->${JSON.stringify(err)}`);
}

privacyManager.off

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

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

If no callback is passed in privacyManager.off, all callbacks of permissionList will be unregistered.

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 permissions. The value must be the same as that of on(). If this parameter is left empty, this API unsubscribes from the permission usage change of all permissions. Valid permission names can be obtained in the Application Permission List.
callbackCallback<ActiveChangeResponse>NoCallback for the permission usage change event.

Error codes

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

IDError Message
12100001The permissionNames in the list are all invalid, or the list size exceeds 1024 bytes.
12100004The interface is not used together with 'on'.
12100007Service is abnormal.
12100008Out of memory.

Example

import privacyManager, { Permissions } from '@ohos.privacyManager';

let permissionList: Array<Permissions> = [];
try {
    privacyManager.off('activeStateChange', permissionList);
}catch(err) {
    console.log(`catch 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 (invoker).
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

NameTypeMandatoryDescription
beginTimenumberYesStart time of the query, in ms.
endTimenumberYesEnd time of the query, in ms.
bundleRecordsArray<BundleUsedRecord>YesPermission usage records.

BundleUsedRecord

Represents the permission access records of an application.

System capability: SystemCapability.Security.AccessToken

NameTypeMandatoryDescription
tokenIdnumberYesToken ID of the application (invoker).
isRemotebooleanYesWhether the token ID belongs to the application on a remote device. The default value is false.
deviceIdstringYesID of the device hosting the target application.
bundleNamestringYesBundle name of the target application.
permissionRecordsArray<PermissionUsedRecord>YesPermission usage records of the target application.

PermissionUsedRecord

Represents the usage records of a permission.

System capability: SystemCapability.Security.AccessToken

NameTypeMandatoryDescription
permissionNamePermissionsYesName of the permission.
accessCountnumberYesTotal number of times that the permission is accessed.
rejectCountnumberYesTotal number of times that the access to the permission is rejected.
lastAccessTimenumberYesLast time when the permission was accessed, accurate to ms.
lastRejectTimenumberYesLast time when the access to the permission was rejected, accurate to ms.
lastAccessDurationnumberYesLast access duration, in ms.
accessRecordsArray<UsedRecordDetail>YesSuccessful access records. This parameter is valid only when flag is FLAG_PERMISSION_USAGE_DETAIL. By default, 10 records are provided.
rejectRecordsArray<UsedRecordDetail>YesRejected 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

NameTypeMandatoryDescription
statusnumberYesAccess status.
lockScreenStatus11+numberNoStatus 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.
timestampnumberYesAccess timestamp, in ms.
accessDurationnumberYesAccess duration, in ms.
count11+numberNoNumber of successful or failed accesses.

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
tokenIdnumberYesNoToken ID of the application.
permissionNamePermissionsYesNoName of the permission.
deviceIdstringYesNoDevice ID.
activeStatusPermissionActiveStatusYesNoPermission usage status.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

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