《第11讲:获取设备信息:型号、OS版本、屏幕DPI》
本文介绍了在Flutter与鸿蒙(OpenHarmony)混合开发中获取设备信息的方法。通过@ohos.systemParameter和@ohos.display系统API,可以获取设备型号、制造商、OS版本、API版本和屏幕DPI等信息。文章详细展示了ArkTS桥接实现代码,包括设备信息获取和WebView注册过程,以及Flutter侧的调用示例。这些信息可用于UI适配(如根据DPI加载不同资源
·
第11篇:获取设备信息:型号、OS版本、屏幕DPI
# Flutter × 鸿蒙实战30讲(11):获取设备信息:型号、OS版本、屏幕DPI
> 作者:烟云任平生
> 发布时间:2025年12月11日
> 标签:`#Flutter` `#OpenHarmony` `#设备信息` `#系统API` `#CSDN`
---
### 一、应用场景
- 上报设备信息用于分析
- 根据屏幕 DPI 调整 UI 缩放
- 判断 OS 版本启用特定功能
---
### 二、所需 API
OpenHarmony 提供 `@ohos.systemParameter` 和 `@ohos.display` 获取设备信息。
---
### 三、ArkTS 实现设备信息桥接
```ts
// deviceBridge.ts
import param from '@ohos.systemParameter';
import display from '@ohos.display';
export class DeviceBridge {
static getDeviceInfo(): Record<string, string> {
return {
model: param.getSync('const.product.model', 'Unknown'),
manufacturer: param.getSync('const.product.manufacturer', 'OpenHarmony'),
osVersion: param.getSync('const.ohos.version.release', '4.1'),
apiVersion: param.getSync('const.ohos.apiversion', '10'),
screenDensity: this.getScreenDensity().toString()
};
}
private static getScreenDensity(): number {
try {
const defaultDisplay = display.getDefaultDisplaySync();
return defaultDisplay?.densityDpi || 160;
} catch (e) {
return 160;
}
}
}
四、注册到 WebView
// MainPage.ets
aboutToAppear() {
this.controller.registerJavaScriptProxy({
object: {
getDeviceInfo: () => {
return JSON.stringify(DeviceBridge.getDeviceInfo());
}
},
name: "DeviceAPI",
interface: ["getDeviceInfo"]
});
}
五、Flutter 侧调用
Future<Map<String, dynamic>> getDeviceDetails() async {
final bridge = html.window['DeviceAPI'];
if (bridge != null) {
final jsonStr = await bridge.callMethod('getDeviceInfo');
return jsonDecode(jsonStr as String);
}
return {};
}
// 使用示例
void printDeviceInfo() async {
final info = await getDeviceDetails();
print('Model: ${info['model']}');
print('DPI: ${info['screenDensity']}');
}
六、典型用途
UI 适配:若 DPI > 320,启用高清资源
功能开关:仅在 API ≥ 10 时启用新特性
埋点上报:将设备信息随日志上传
🔜 下一篇预告:《第12讲:实现通知推送:OpenHarmony 通知中心集成》
🌟 关注我,持续解锁 Flutter + 鸿蒙的更多能力!
更多推荐
所有评论(0)