关注

Cordova 设备信息集成教程目录

  1. 简介

  2. 前置条件

  3. 设备信息 API 概述

  4. 实现步骤

  5. 完整代码示例

  6. 设备信息属性说明

  7. 常见问题

  8. 最佳实践


简介

在 Cordova 应用中,获取设备信息是一个常见的需求。通过使用 Cordova 的 Device API,我们可以轻松获取设备的型号、操作系统版本、唯一标识符等信息。本教程将详细介绍如何在 Cordova 应用中集成设备信息获取功能,并将信息展示在页面上。

前置条件

在开始之前,请确保:

  1. 已安装 Cordova CLI

    npm install -g cordova
    # 或对于 HarmonyOS
    npm install -g hcordova
  2. 已创建 Cordova 项目

    cordova create MyApp com.example.myapp MyApp
    cd MyApp
  3. 已添加目标平台

    cordova platform add android
    # 或
    cordova platform add ios
    # 或
    hcordova platform add harmonyos
  4. Device 插件已安装(Cordova 核心插件,通常已包含)

在 Cordova 项目根目录执行以下命令,自动下载并集成插件:
​
安装hcordova
npm install -g hcordova
​
安装最新稳定版
​
hcordova plugin add cordova-plugin-device
​
指定平台安装
​
hcordova plugin add cordova-plugin-device --platform harmonyos
​
​


设备信息 API 概述

Cordova 的 Device API 提供了以下设备信息属性:

属性类型说明示例值
device.modelString设备型号或产品名称"iPhone 13 Pro"
device.platformString操作系统名称"iOS", "Android", "HarmonyOS"
device.uuidString设备的唯一标识符"550e8400-e29b-41d4-a716-446655440000"
device.versionString操作系统版本"15.0", "12.0"
device.manufacturerString设备制造商"Apple", "Samsung"
device.isVirtualBoolean是否为虚拟设备(模拟器)true/false
device.serialString设备序列号"C39VXXXXX"

实现步骤

步骤 1: 监听设备就绪事件

在 Cordova 应用中,必须等待 deviceready 事件触发后才能访问设备 API。这是因为 Cordova 需要时间初始化原生代码桥接。

// 等待 Cordova 设备就绪事件
document.addEventListener("deviceready", onDeviceReady, false);

步骤 2: 创建设备信息获取函数

deviceready 事件触发后,创建一个函数来获取和打印设备信息:

function onDeviceReady() {
   console.log("Cordova 设备就绪,开始获取设备信息...");
​
   // 打印所有核心设备属性
   console.log("设备型号(model):", device.model);
   console.log("操作系统(platform):", device.platform);
   console.log("设备唯一标识(uuid):", device.uuid);
   console.log("系统版本(version):", device.version);
   console.log("设备制造商(manufacturer):", device.manufacturer);
   console.log("是否为虚拟设备(isVirtual):", device.isVirtual);
   console.log("设备序列号(serial):", device.serial);
​
   // 在页面上显示设备信息
   displayDeviceInfo();
}

步骤 3: 创建页面显示函数

创建一个函数来在页面上动态显示设备信息:

function displayDeviceInfo() {
   // 创建设备信息容器
   const deviceInfoContainer = document.createElement('div');
   deviceInfoContainer.id = 'device-info';
   deviceInfoContainer.style.cssText = `
       max-width: 600px;
       margin: 20px auto;
       padding: 20px;
       background-color: #fff;
       border-radius: 8px;
       box-shadow: 0 2px 10px rgba(0,0,0,0.1);
   `;
​
   // 创建标题
   const title = document.createElement('h2');
   title.textContent = '设备信息';
   title.style.cssText = 'color: #2c3e50; margin-bottom: 15px; text-align: center;';
   deviceInfoContainer.appendChild(title);
​
   // 创建信息列表
   const infoList = document.createElement('div');
   infoList.style.cssText = 'font-size: 14px; line-height: 1.8;';
​
   // 定义设备信息数组
   const deviceInfo = [
      { label: '设备型号', value: device.model || '未知' },
      { label: '操作系统', value: device.platform || '未知' },
      { label: '系统版本', value: device.version || '未知' },
      { label: '设备制造商', value: device.manufacturer || '未知' },
      { label: '设备唯一标识', value: device.uuid || '未知' },
      { label: '设备序列号', value: device.serial || '未知' },
      { label: '是否为虚拟设备', value: device.isVirtual !== undefined ? (device.isVirtual ? '是' : '否') : '未知' }
  ];
​
   // 遍历设备信息并创建显示元素
   deviceInfo.forEach(info => {
       const infoItem = document.createElement('div');
       infoItem.style.cssText = 'margin-bottom: 10px; padding: 8px; background-color: #f8f9fa; border-radius: 4px;';
       
       const label = document.createElement('strong');
       label.textContent = info.label + ':';
       label.style.cssText = 'color: #2980b9; margin-right: 8px;';
       
       const value = document.createElement('span');
       value.textContent = info.value;
       value.style.cssText = 'color: #555;';
       
       infoItem.appendChild(label);
       infoItem.appendChild(value);
       infoList.appendChild(infoItem);
  });
​
   deviceInfoContainer.appendChild(infoList);
​
   // 将设备信息添加到页面
   const appDiv = document.querySelector('.app');
   if (appDiv && appDiv.parentNode) {
       appDiv.parentNode.insertBefore(deviceInfoContainer, appDiv.nextSibling);
  } else {
       document.body.appendChild(deviceInfoContainer);
  }
}

步骤 4: 更新 HTML 文件

在 HTML 文件中确保引入了 Cordova 脚本:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>设备信息示例</title>
   <link rel="stylesheet" href="css/index.css">
</head>
<body>
   <div class="app">
       <h1>Apache Cordova</h1>
       <div id="deviceready" class="blink">
           <p class="event listening">Connecting to Device</p>
           <p class="event received">Device is Ready</p>
       </div>
   </div>
   
   <!-- 设备信息将在这里动态显示 -->
   <div id="device-info-placeholder"></div>
   
   <!-- 重要:必须先加载 cordova.js -->
   <script src="cordova.js"></script>
   <script src="js/index.js"></script>
</body>
</html>

完整代码示例

www/js/index.js 完整代码

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
​
// 等待 Cordova 设备就绪事件
document.addEventListener('deviceready', onDeviceReady, false);
​
function onDeviceReady() {
   // Cordova 现在已初始化
   console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
   document.getElementById('deviceready').classList.add('ready');
​
   // 获取并打印设备信息
   console.log("Cordova 设备就绪,开始获取设备信息...");
​
   // 打印所有核心设备属性
   console.log("设备型号(model):", device.model);
   console.log("操作系统(platform):", device.platform);
   console.log("设备唯一标识(uuid):", device.uuid);
   console.log("系统版本(version):", device.version);
   console.log("设备制造商(manufacturer):", device.manufacturer);
   console.log("是否为虚拟设备(isVirtual):", device.isVirtual);
   console.log("设备序列号(serial):", device.serial);
​
   // 在页面上显示设备信息
   displayDeviceInfo();
}
​
function displayDeviceInfo() {
   // 创建设备信息容器
   const deviceInfoContainer = document.createElement('div');
   deviceInfoContainer.id = 'device-info';
   deviceInfoContainer.style.cssText = `
       max-width: 600px;
       margin: 20px auto;
       padding: 20px;
       background-color: #fff;
       border-radius: 8px;
       box-shadow: 0 2px 10px rgba(0,0,0,0.1);
   `;
​
   // 创建标题
   const title = document.createElement('h2');
   title.textContent = '设备信息';
   title.style.cssText = 'color: #2c3e50; margin-bottom: 15px; text-align: center;';
   deviceInfoContainer.appendChild(title);
​
   // 创建信息列表
   const infoList = document.createElement('div');
   infoList.style.cssText = 'font-size: 14px; line-height: 1.8;';
​
   const deviceInfo = [
      { label: '设备型号', value: device.model || '未知' },
      { label: '操作系统', value: device.platform || '未知' },
      { label: '系统版本', value: device.version || '未知' },
      { label: '设备制造商', value: device.manufacturer || '未知' },
      { label: '设备唯一标识', value: device.uuid || '未知' },
      { label: '设备序列号', value: device.serial || '未知' },
      { label: '是否为虚拟设备', value: device.isVirtual !== undefined ? (device.isVirtual ? '是' : '否') : '未知' }
  ];
​
   deviceInfo.forEach(info => {
       const infoItem = document.createElement('div');
       infoItem.style.cssText = 'margin-bottom: 10px; padding: 8px; background-color: #f8f9fa; border-radius: 4px;';
       
       const label = document.createElement('strong');
       label.textContent = info.label + ':';
       label.style.cssText = 'color: #2980b9; margin-right: 8px;';
       
       const value = document.createElement('span');
       value.textContent = info.value;
       value.style.cssText = 'color: #555;';
       
       infoItem.appendChild(label);
       infoItem.appendChild(value);
       infoList.appendChild(infoItem);
  });
​
   deviceInfoContainer.appendChild(infoList);
​
   // 将设备信息添加到页面
   const appDiv = document.querySelector('.app');
   if (appDiv && appDiv.parentNode) {
       appDiv.parentNode.insertBefore(deviceInfoContainer, appDiv.nextSibling);
  } else {
       document.body.appendChild(deviceInfoContainer);
  }
}

设备信息属性说明

1. device.model

  • 说明: 返回设备的型号或产品名称

  • 示例:

    • iOS: "iPhone 13 Pro"

    • Android: "SM-G991B"

    • HarmonyOS: "Mate 40 Pro"

2. device.platform

  • 说明: 返回设备的操作系统名称

  • 可能的值:

    • "iOS"

    • "Android"

    • "HarmonyOS"

    • "Windows"

    • "browser" (在浏览器中运行时)

3. device.uuid

  • 说明: 返回设备的唯一标识符(UUID)

  • 注意:

    • iOS: 返回设备的 UUID,每个应用实例可能不同

    • Android: 返回 Android ID(64位随机数)

    • 这个值在同一设备上可能因应用而异

4. device.version

  • 说明: 返回操作系统的版本号

  • 示例:

    • iOS: "15.0"

    • Android: "12"

    • HarmonyOS: "6.0"

5. device.manufacturer

  • 说明: 返回设备制造商名称

  • 示例: "Apple", "Samsung", "Huawei"

6. device.isVirtual

  • 说明: 返回设备是否为虚拟设备(模拟器/仿真器)

  • 类型: Boolean

  • 示例:

    • 真实设备: false

    • 模拟器: true

7. device.serial

  • 说明: 返回设备的硬件序列号

  • 注意:

    • iOS: 可能不可用

    • Android: 需要 READ_PHONE_STATE 权限

    • 某些设备可能返回 "unknown"


常见问题

Q1: 为什么 deviceready 事件没有触发?

A: 可能的原因:

  1. 没有正确加载 cordova.js 文件

  2. 在浏览器中测试(需要使用模拟器或真实设备)

  3. 脚本加载顺序错误(必须先加载 cordova.js

解决方案:

<!-- 正确的加载顺序 -->
<script src="cordova.js"></script>
<script src="js/index.js"></script>

Q2: 某些设备属性返回 undefinednull

A: 这是正常的,因为:

  1. 不同平台支持的属性可能不同

  2. 某些属性需要特定权限

  3. 某些属性在模拟器上可能不可用

解决方案: 使用默认值处理:

const model = device.model || '未知';
const serial = device.serial || '不可用';

Q3: 在浏览器中测试时设备信息不可用

A: Cordova Device API 只能在原生应用中运行,浏览器中会返回默认值。

解决方案:

  • 使用 cordova serve 在浏览器中测试 UI

  • 使用模拟器或真实设备测试设备信息功能

Q4: 如何获取更多设备信息?

A: 可以使用其他 Cordova 插件:

  • cordova-plugin-device-motion: 获取设备运动信息

  • cordova-plugin-device-orientation: 获取设备方向

  • cordova-plugin-battery-status: 获取电池状态

  • cordova-plugin-network-information: 获取网络信息


最佳实践

1. 错误处理

始终对设备属性进行空值检查:

function getDeviceInfo() {
    return {
        model: device.model || '未知',
        platform: device.platform || '未知',
        version: device.version || '未知',
        manufacturer: device.manufacturer || '未知',
        uuid: device.uuid || '未知',
        serial: device.serial || '不可用',
        isVirtual: device.isVirtual !== undefined ? device.isVirtual : null
    };
}

2. 异步处理

虽然 Device API 是同步的,但建议在 deviceready 事件中处理:

document.addEventListener('deviceready', function() {
    // 确保设备 API 已完全初始化
    if (typeof device !== 'undefined') {
        displayDeviceInfo();
    } else {
        console.error('Device API 不可用');
    }
}, false);

3. 性能优化

如果需要在多个地方使用设备信息,可以缓存结果:

let cachedDeviceInfo = null;

function getDeviceInfo() {
    if (!cachedDeviceInfo) {
        cachedDeviceInfo = {
            model: device.model || '未知',
            platform: device.platform || '未知',
            // ... 其他属性
        };
    }
    return cachedDeviceInfo;
}

4. 响应式设计

确保设备信息显示在不同屏幕尺寸上都能正常显示:

#device-info {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
}

@media (max-width: 768px) {
    #device-info {
        padding: 15px;
        margin: 10px;
    }
}

5. 隐私和安全

  • UUID: 不要将 UUID 用于用户身份识别,因为它可能因应用而异

  • 序列号: 某些平台需要特殊权限才能获取

  • 敏感信息: 避免在日志中记录敏感的设备信息


测试建议

1. 在不同平台上测试

  • iOS 设备/模拟器

  • Android 设备/模拟器

  • HarmonyOS 设备/模拟器

  • 浏览器(用于 UI 测试)

2. 测试场景

  • 真实设备

  • 模拟器/仿真器

  • 不同操作系统版本

  • 不同设备型号

3. 调试技巧

使用 console.log 输出设备信息:

console.log('设备信息:', {
    model: device.model,
    platform: device.platform,
    version: device.version,
    // ...
});

总结

通过本教程,您已经学会了:

  1. ✅ 如何在 Cordova 应用中获取设备信息

  2. ✅ 如何监听 deviceready 事件

  3. ✅ 如何在页面上动态显示设备信息

  4. ✅ 如何处理设备属性的空值情况

  5. ✅ 了解了各个设备属性的含义和用途

现在您可以在自己的 Cordova 应用中集成设备信息功能了!


参考资料


作者: 坚果派开发团队 最后更新: 2025年 版本: 1.0

转载自CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/2401_83596468/article/details/155102421

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--