HarmonyOS 鸿蒙Next中如何使用 @PrivacyConsentManager 管理用户同意记录?

HarmonyOS 鸿蒙Next中如何使用 @PrivacyConsentManager 管理用户同意记录? **问题描述:**应用需记录用户对隐私协议、权限、数据使用的同意状态(如同意时间、协议版本、授权范围),以便后续审计、用户查询或撤回,等合规要求。

3 回复

详细回答:

HarmonyOS 未提供名为 @PrivacyConsentManager 的系统级 API,但开发者应封装一个隐私同意管理器类,用于:存储用户同意的协议版本号、记录同意时间戳、保存授权的具体权限/数据类型、支持同意状态查询与撤回、数据应加密存储,防止篡改。@PrivacyConsentManager 是对“隐私同意管理模块”的逻辑抽象,实际通过自定义工具类实现。

✅ 正确做法

/**
 * @author J.query
 * @date 2025/12/26 23:15
 * @email j-query@foxmail.com
 * Description:
 */
import { preferences } from "@kit.ArkData";


const CONSENT_PREFS_NAME = 'privacy_consent_v1';

export interface ConsentRecord {
  version: string;          // 隐私协议版本,如 "v1.1"
  timestamp: number;        // 同意时间戳(毫秒)
  grantedPermissions: string[]; // 授权的权限列表,如 ['CAMERA', 'LOCATION']
  dataCategories: string[]; // 允许收集的数据类型,如 ['DEVICE_ID', 'USAGE_LOG']
}

export class PrivacyConsentManager {
  private prefs: preferences.Preferences;

  constructor(context: Context) {
    // 修复错误:使用正确的 Options 参数格式
    const options: preferences.Options = {
      name: CONSENT_PREFS_NAME
    };
    this.prefs = preferences.getPreferencesSync(context, options);
  }

  // 记录用户同意
  async recordConsent(record: ConsentRecord): Promise<void> {
    const jsonStr = JSON.stringify(record);
    // 存储为字符串(生产环境建议加密)
    this.prefs.putSync('user_consent', jsonStr);
    await this.prefs.flushSync();
    console.log('✅ 隐私同意已记录');
  }

  // 查询当前同意状态
  getConsent(): ConsentRecord | null {
    const value = this.prefs.getSync('user_consent', '');
    // 检查 value 是否为字符串类型
    if (typeof value !== 'string' || !value) return null;
    try {
      return JSON.parse(value);
    } catch (e) {
      console.error('❌ 同意记录解析失败:', e);
      return null;
    }
  }

  // 用户撤回同意
  async revokeConsent(): Promise<void> {
    this.prefs.deleteSync('user_consent');
    await this.prefs.flushSync();
    console.log('⚠️ 用户已撤回隐私同意');
    // TODO: 触发数据清除、停止数据收集等操作
  }

  // 检查是否需要重新获取同意(如协议升级)
  shouldRequestNewConsent(currentPolicyVersion: string): boolean {
    const record = this.getConsent();
    if (!record) return true;
    // 简单版本比较(实际可用 semver 库)
    return record.version !== currentPolicyVersion;
  }
}

// 导出单例(按 Ability 实例隔离)
let instance: PrivacyConsentManager | null = null;
export function getPrivacyConsentManager(context: Context): PrivacyConsentManager {
  if (!instance) {
    instance = new PrivacyConsentManager(context);
  }
  return instance;
}

在页面中使用:

/**
 * @author J.query
 * @date 2025/12/26 23:16
 * @email j-query@foxmail.com
 * Description:
 */

// pages/PrivacyPage.ets
import { getPrivacyConsentManager, PrivacyConsentManager } from '../utils/PrivacyConsentManager';

const CURRENT_POLICY_VERSION = 'v2.3'; // 当前隐私协议版本

@Entry
@Component
struct PrivacyPage {
  private consentManager: PrivacyConsentManager | null = null;
  @State isAgreed: boolean = false;
  @State showPolicy: boolean = false;

  aboutToAppear() {
    this.consentManager = getPrivacyConsentManager(getContext(this));
    const record = this.consentManager?.getConsent();
    this.isAgreed = !!record && !this.consentManager?.shouldRequestNewConsent(CURRENT_POLICY_VERSION);
  }

  onAgree() {
    if (!this.consentManager) {
      console.error('❌ Consent manager is not initialized');
      return;
    }
    
    const record: import("../utils/PrivacyConsentManager").ConsentRecord = {
      version: CURRENT_POLICY_VERSION,
      timestamp: Date.now(),
      grantedPermissions: ['ohos.permission.ACCESS_FINE_LOCATION'],
      dataCategories: ['DEVICE_ID', 'APP_USAGE']
    };
    this.consentManager.recordConsent(record);
    this.isAgreed = true;
  }

  onRevoke() {
    if (!this.consentManager) {
      console.error('❌ Consent manager is not initialized');
      return;
    }
    
    this.consentManager.revokeConsent();
    this.isAgreed = false;
  }

  build() {
    Column() {
      if (!this.isAgreed) {
        Text('请阅读并同意隐私协议')
          .fontSize(18)
          .margin({ bottom: 20 })
        Button('查看隐私协议')
          .onClick(() => this.showPolicy = true)
        Button('同意')
          .onClick(() => this.onAgree())
          .margin({ top: 10 })
      } else {
        Text('您已同意隐私协议 v2.3')
        Button('撤回同意')
          .onClick(() => this.onRevoke())
          .backgroundColor('#ff4d4f')
      }
    }
    .padding(20)
  }
}
  • ⚠️ 避坑指南
    1. 不要硬编码协议内容:隐私协议文本应从服务器动态加载,避免因协议更新需强制升级 App。
    2. 敏感字段需加密:生产环境中,user_consent 的 JSON 字符串应使用 huks 加密后再存储。
    3. 无现成 [@PrivacyConsentManager](/user/PrivacyConsentManager),但通过自定义管理器 + 安全存储 + 版本控制,可完全满足 法规对“用户同意记录”的强制要求,这是高合规性应用的必备能力。

🎯 效果

cke_39128.png cke_44260.png

更多关于HarmonyOS 鸿蒙Next中如何使用 @PrivacyConsentManager 管理用户同意记录?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用@PrivacyConsentManager管理用户同意记录,需导入@kit.PrivacyConsentManager模块。通过getInstance()获取管理器实例,调用grant()方法授予权限,revoke()方法撤销权限,check()方法检查权限状态。权限变更可通过on()监听事件。操作需在entryfeature模块的module.json5中声明相应权限。

在HarmonyOS Next中,@PrivacyConsentManager 是用于管理用户隐私同意记录的核心API。以下是具体使用方法:

1. 导入模块

import { privacyConsentManager } from '@kit.PrivacyConsentKit';

2. 记录用户同意

当用户同意隐私协议时,记录同意状态:

// 记录隐私协议同意
const consentRecord: privacyConsentManager.PrivacyConsentRecord = {
  type: privacyConsentManager.ConsentType.PRIVACY_POLICY, // 同意类型
  version: '2.0.0', // 协议版本
  status: privacyConsentManager.ConsentStatus.AGREED, // 同意状态
  scope: ['data_collection', 'personalized_ads'], // 授权范围
  timestamp: new Date().toISOString() // 同意时间
};

try {
  await privacyConsentManager.addConsentRecord(consentRecord);
} catch (error) {
  console.error('记录同意失败:', error);
}

3. 查询同意记录

查询特定类型的同意记录:

// 查询隐私协议同意记录
const records = await privacyConsentManager.queryConsentRecords(
  privacyConsentManager.ConsentType.PRIVACY_POLICY
);

// 获取最新记录
const latestRecord = records[records.length - 1];

4. 处理用户撤回

当用户撤回同意时,更新记录:

const withdrawRecord: privacyConsentManager.PrivacyConsentRecord = {
  type: privacyConsentManager.ConsentType.PRIVACY_POLICY,
  version: '2.0.0',
  status: privacyConsentManager.ConsentStatus.WITHDRAWN, // 撤回状态
  timestamp: new Date().toISOString()
};

await privacyConsentManager.addConsentRecord(withdrawRecord);

5. 关键配置

module.json5中声明隐私权限:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.PRIVACY_CONSENT_MANAGER"
      }
    ]
  }
}

注意事项

  • 同意记录会持久化存储,应用卸载后自动清除
  • 每次同意变更都应创建新记录,保持完整的审计轨迹
  • 建议在应用启动时检查最新同意状态,确保功能合规
  • 授权范围(scope)需与应用实际数据处理行为对应

通过以上方法,可以完整记录用户同意生命周期,满足合规审计要求。

回到顶部