1# 用户偏好 2 3<!--Kit: Localization Kit--> 4<!--Subsystem: Global--> 5<!--Owner: @yliupy--> 6<!--Designer: @sunyaozu--> 7<!--Tester: @lpw_work--> 8<!--Adviser: @Brilliantry_Rui--> 9 10## 使用场景 11 12除区域设置和应用偏好语言设置外,系统还可以设置用户偏好,当前支持本地数字和时制两种偏好。用户偏好设置会保存到系统区域及应用偏好语言中,最终体现在用户界面的国际化特性上。 13 14## 开发步骤 15 16接口具体使用方法和说明请参考[System](../reference/apis-localization-kit/js-apis-i18n.md#system9)的API接口文档。 17 181. 导入模块。 19 ```ts 20 import { i18n } from '@kit.LocalizationKit'; 21 import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; 22 ``` 23 242. 获取用户偏好。 25 ```ts 26 // 判断系统当前是否使用本地数字 27 let usingLocalDigit: boolean = i18n.System.getUsingLocalDigit(); 28 29 // 判断系统当前是否使用24小时制 30 let is24HourClock: boolean = i18n.System.is24HourClock(); 31 32 // 通过监听公共事件COMMON_EVENT_TIME_CHANGED可以感知系统时制变化 33 let subscriber: commonEventManager.CommonEventSubscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 34 let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { 35 events: [commonEventManager.Support.COMMON_EVENT_TIME_CHANGED] 36 }; 37 // 创建订阅者 38 commonEventManager.createSubscriber(subscribeInfo) 39 .then((commonEventSubscriber: commonEventManager.CommonEventSubscriber) => { 40 console.info("CreateSubscriber"); 41 subscriber = commonEventSubscriber; 42 commonEventManager.subscribe(subscriber, (err, data) => { 43 if (err) { 44 console.error(`Failed to subscribe common event. error code: ${err.code}, message: ${err.message}.`); 45 return; 46 } 47 // 用于区分系统时间和系统时制变化 48 if (data.data != undefined && data.data == '24HourChange') { 49 console.info("The subscribed event has occurred."); // 系统时制变化时执行 50 } 51 }) 52 }) 53 .catch((err: BusinessError) => { 54 console.error(`CreateSubscriber failed, code is ${err.code}, message is ${err.message}`); 55 }); 56 ``` 57 58<!--Del--> 593. 设置使用本地数字。 60 ```ts 61 try { 62 i18n.System.setUsingLocalDigit(true); // 使用本地数字 63 } catch (error) { 64 let err: BusinessError = error as BusinessError; 65 console.error(`call System.setUsingLocalDigit failed, error code: ${err.code}, message: ${err.message}.`); 66 } 67 ``` 68 694. 设置时间显示格式为24小时制。 70 ```ts 71 try { 72 i18n.System.set24HourClock(true); // 设置系统时制为24小时制 73 } catch (error) { 74 let err: BusinessError = error as BusinessError; 75 console.error(`call System.set24HourClock failed, error code: ${err.code}, message: ${err.message}.`); 76 } 77 ``` 78<!--DelEnd--> 79