当前位置: 首页 > article >正文

HarmonyOS 设备管理

1. HarmonyOS设备管理

在这里插入图片描述

1.1. 说明

  文档中心:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-device-info-V5
在这里插入图片描述
  HarmonyOS设备管理分为电源管理、设备管理、系统电源管理、Runninglock锁、热管理、USB管理等。

1.2. 设备屏幕属性

  文档中心:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-display-V5?catalogVersion=V5
  基于 ArkUI 中 display 的 getDefaultDisplaySync 方法实现获取屏幕宽高尺寸,除此之外 api 中提供一些分辨率之类的参数,具体可参考官网文档按需增配;
  @ohos.display屏幕属性提供管理显示设备的一些基础能力,包括获取默认显示设备的信息,获取所有显示设备的信息以及监听显示设备的插拔行为。我们可以通过该组件获取屏幕的宽高等信息

1.2.1. 获取屏幕属性的方法

  在@Component的aboutToAppear方法调用@ohos.display的相关API,可以获取屏幕的属性。@ohos.display提供了三个获取屏幕属性的方法:getDefaultDisplay(callback: AsyncCallback)、getDefaultDisplay()、getAllDisplay(callback: AsyncCallback<Array>)方法。

1.2.1.1. getDefaultDisplay(callback: AsyncCallback)的用法

  在使用的时候,需要import display from '@ohos.display’引入组件。

//引入@ohos.display组件
import display from '@ohos.display';
@Entry
@Component
struct Index {
  aboutToAppear() {
    // 获取屏幕宽高
    display.getDefaultDisplay((err, data) => {
      if (err) {
        console.error('Failed to obtain the default display object. Code:  ' + JSON.stringify(err));
        return;
      }
      console.info(JSON.stringify(data));
    });
  }
}

  输入为:

{
    "alive":true,
    "densityDPI":560,
    "densityPixels":3.5,
    "height":2560,
    "id":0,
    "name":"内置屏幕",
    "refreshRate":60.000004,
    "rotation":0,
    "scaledDensity":3.5,
    "state":2,
    "width":1440,
    "xDPI":560,
    "yDPI":560
}
1.2.1.2. getDefaultDisplay()的用法

  获取当前默认的display对象。使用Promise异步回调。该方法返回的是Promise

  let promise = display.getDefaultDisplay();
    promise.then((data) => {//此处data为Display对象
      console.info(JSON.stringify(data));
    }).catch((err) => {
      console.info( JSON.stringify(err));
    });

  输出同getDefaultDisplay(callback: AsyncCallback)

1.2.1.3. getAllDisplay(callback: AsyncCallback)的用法

  获取当前所有的display对象。使用Promise异步回调。返回的是json数组。

    display.getAllDisplay((err, data) => {
      if (err) {
        console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
        return;
      }
      console.info(JSON.stringify(data))
    });

  输出为JSON数组:

[
    {
        "alive":true,
        "densityDPI":560,
        "densityPixels":3.5,
        "height":2560,
        "id":0,
        "name":"内置屏幕",
        "refreshRate":60.000004,
        "rotation":0,
        "scaledDensity":3.5,
        "state":2,
        "width":1440,
        "xDPI":560,
        "yDPI":560
    }
]
1.2.1.4. getDefaultDisplaySync()的用法

  也可以使用getDefaultDisplaySync方法获取屏幕宽高:

let screenWidth = display.getDefaultDisplaySync().width;
  let screenHeight = display.getDefaultDisplaySync().height;

  也可以调用getAllDisplays来获取,同时调用px2vp将px转换成vp

  aboutToAppear() {
    display.getAllDisplays((err, data) => {
      // 拿到屏幕宽高的一半,作为判断基准值
      this.displayHalfWidth = data[0].width / 2;
      this.displayHalfHeight = data[0].height / 2;
      // 将拿到的px转为vp
      Logger.info(TAG, `aboutToAppear getAllDisplays data 1 width:${this.displayHalfWidth}, height:${this.displayHalfHeight}`);
      this.displayHalfWidth = px2vp(this.displayHalfWidth);
      this.displayHalfHeight = px2vp(this.displayHalfHeight);
      Logger.info(TAG, `aboutToAppear getAllDisplays data 2 width:${this.displayHalfWidth}, height:${this.displayHalfHeight}`);
    })
  }

1.2.2. 代码实现

1.2.2.1. ScreenUtils
import display from '@ohos.display'

export class ScreenUtils {
  //屏幕数据
  private defaultDisplay: display.Display | null = null

  private static instance: ScreenUtils;

  private constructor(){
    this.defaultDisplay = display.getDefaultDisplaySync()
  }

  public static getInstance(): ScreenUtils {
    if (!ScreenUtils.instance) {
      ScreenUtils.instance = new ScreenUtils();
    }
    return ScreenUtils.instance;
  }

  //屏幕宽度--px单位
  getScreenWidthPx(): number {
    return this.defaultDisplay?.width ?? -1
  }

  //屏幕宽度--px单位转换成vp单位,鸿蒙适配vp单位
  getScreenWidthVp(): number {
    return px2vp(this.getScreenWidthPx())
  }

  //屏幕高度--px单位
  getScreenHeightPx(): number {
    return this.defaultDisplay?.height ?? -1
  }

  //屏幕高度--vp单位
  getScreenHeightVp(): number {
    return px2vp(this.getScreenHeightPx())
  }
}
1.2.2.2. PagePage
import { promptAction, router } from '@kit.ArkUI'
import { RouterParams } from 'zzslib'
import { TitleBar } from '../../../components/common/TitleBar'
import display from '@ohos.display';
import { ScreenUtils } from '../../../utils/ScreenUtils';

@Extend(Button)
function buttonItem() {
  .stateEffect(true)
  .type(ButtonType.Normal)
  .borderRadius(8)
  .fontSize(17)
  .backgroundColor($r('app.color.primary_green'))
  .padding({
    top: 8,
    bottom: 8,
    left: 70,
    right: 70
  })
  .margin({
    top: 15,
    bottom: 15
  })
}

@Entry
@Component
struct PagePage {
  @State pageTitle: string = "页面属性"
  @State msg: string = ''

  aboutToAppear() {
    try {
      this.pageTitle = (router
        .getParams() as RouterParams).title
    } catch (e) {
    }
  }

  /**
   * 获取类,方法
   */
  private myClick() {
    let that = this
    let data = display.getDefaultDisplaySync();
    let screenWidth = px2vp(data.width) //屏幕宽
    let screenHeight = px2vp(data.height) //屏幕高
    let screenUtils: ScreenUtils = ScreenUtils.getInstance();
    let screenWidth21 = screenUtils.getScreenWidthVp() //屏幕宽
    let screenHeight21 = screenUtils.getScreenHeightVp() //屏幕高
    let screenWidth22 = screenUtils.getScreenWidthPx() //屏幕宽
    let screenHeight22 = screenUtils.getScreenHeightPx() //屏幕高
    that.msg = "屏幕密度:" + data.densityDPI
      + "\n屏幕像素点:" + data.densityPixels
      + "\n屏幕刷新率:" + data.refreshRate
      + "\n屏幕方向:" + data.orientation
      + "\n屏幕可用宽:" + data.availableWidth
      + "\n屏幕可用高:" + data.availableHeight
      + "\n屏幕宽(px):" + data.width
      + "\n屏幕高(px):" + data.height
      + "\n屏幕宽(vp):" + screenWidth
      + "\n屏幕高(vp):" + screenHeight
      + "\n屏幕宽(vp):" + screenWidth21
      + "\n屏幕高(vp):" + screenHeight21
      + "\n屏幕宽(vp):" + screenWidth22
      + "\n屏幕高(vp):" + screenHeight22
  }

  build() {
    Column() {
      TitleBar({ pageTitle: $pageTitle })
      Button('屏幕信息')
        .buttonItem()
        .onClick(() => this.myClick())
      Text(this.msg)

    }
    .height('100%')
  }
}

在这里插入图片描述

1.3. 设备信息

  HarmonyOS设备信息模块提供终端设备信息查询,开发者不可配置。

1.3.1. 说明

  HarmonyOS设备信息首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
  部分参数返回值为default的,会在正式发布的版本中配置。
  模块接口返回设备常量信息,建议应用只调用一次,不需要频繁调用。

1.3.2. 导入模块

import { deviceInfo } from '@kit.BasicServicesKit';

1.3.3. 属性

  说明:未特殊说明的字段,数据长度最大值为96字节。

1.4.3. 代码实现

import { router } from '@kit.ArkUI';
import { TitleBar } from '../../../components/common/TitleBar';
import { AppHelper, BundleInfo, RouterParams } from 'zzslib';
import { deviceInfo } from '@kit.BasicServicesKit';

@Extend(Button)
function buttonItem() {
  .stateEffect(true)
  .type(ButtonType.Normal)
  .borderRadius(8)
  .fontSize(17)
  .backgroundColor($r('app.color.primary_green'))
  .padding({
    top: 8,
    bottom: 8,
    left: 70,
    right: 70
  })
  .margin({
    top: 15,
    bottom: 15
  })
}


@Entry
@Component
struct DevicePage {
  @State pageTitle: string = "设备信息"
  @State message: string = '设备信息';
  private scroller: Scroller = new Scroller()

  aboutToAppear() {
    try {
      this.pageTitle = (router
        .getParams() as RouterParams).title
    } catch (e) {
    }
  }

  /**
   * 获取设备信息
   */
  deviceInfoClick() {
    let that = this;
    let infoStr = "";
    //设备类型
    let deviceType: string = deviceInfo.deviceType;
    infoStr += "设备类型:" + deviceType;
    //制造商
    let manufacture: string = deviceInfo.manufacture;
    infoStr += "\n制造商:" + manufacture;
    //品牌
    let brand: string = deviceInfo.brand;
    infoStr += "\n品牌:" + brand;
    //市场名称
    let marketName: string = deviceInfo.marketName;
    infoStr += "\n市场名称:" + marketName;
    //产品系列
    let productSeries: string = deviceInfo.productSeries;
    infoStr += "\n产品系列:" + productSeries;
    //产品型号
    let productModel: string = deviceInfo.productModel;
    infoStr += "\n产品型号:" + productModel;
    //软件模型
    let softwareModel: string = deviceInfo.softwareModel;
    infoStr += "\n软件模型:" + softwareModel;
    //硬件型号
    let hardwareModel: string = deviceInfo.hardwareModel;
    infoStr += "\n硬件型号:" + hardwareModel;
    //序列号
    let serial: string = deviceInfo.serial;
    infoStr += "\n序列号:" + serial;
    //引导加载程序版本
    let bootloaderVersion: string = deviceInfo.bootloaderVersion;
    infoStr += "\n引导加载程序版本:" + bootloaderVersion;
    //架构列表
    let abiList: string = deviceInfo.abiList;
    infoStr += "\n架构列表:" + abiList;
    //安全补丁
    let securityPatchTag: string = deviceInfo.securityPatchTag;
    infoStr += "\n安全补丁:" + securityPatchTag;
    //设备版本
    let displayVersion: string = deviceInfo.displayVersion;
    infoStr += "\n设备版本:" + displayVersion;
    //增量版本
    let incrementalVersion: string = deviceInfo.incrementalVersion;
    infoStr += "\n增量版本:" + incrementalVersion;
    //系统包类型
    let osReleaseType: string = deviceInfo.osReleaseType;
    infoStr += "\n系统包类型:" + osReleaseType;
    //系统全称
    let osFullNameInfo: string = deviceInfo.osFullName;
    infoStr += "\n系统全称:" + osFullNameInfo;
    //主版本号
    let majorVersion: number = deviceInfo.majorVersion;
    infoStr += "\n主版本号:" + majorVersion;
    //次级版本号
    let seniorVersion: number = deviceInfo.seniorVersion;
    infoStr += "\n次级版本号:" + seniorVersion;
    //特性版本号
    let featureVersion: number = deviceInfo.featureVersion;
    infoStr += "\n特性版本号:" + featureVersion;
    //构建版本号
    let buildVersion: number = deviceInfo.buildVersion;
    infoStr += "\n构建版本号:" + buildVersion;
    //sdkApi版本号
    let sdkApiVersionInfo: number = deviceInfo.sdkApiVersion;
    infoStr += "\nsdkApi版本号:" + sdkApiVersionInfo;
    //firstApi版本号
    let firstApiVersionInfo: number = deviceInfo.firstApiVersion;
    infoStr += "\nfirstApi版本号:" + firstApiVersionInfo;
    //versionId
    let versionId: string = deviceInfo.versionId;
    infoStr += "\nversionId:" + versionId;
    //buildType
    let buildType: string = deviceInfo.buildType;
    infoStr += "\nbuildType:" + buildType;
    //buildUser
    let buildUser: string = deviceInfo.buildUser;
    infoStr += "\nbuildUser:" + buildUser;
    //buildHost
    let buildHost: string = deviceInfo.buildHost;
    infoStr += "\nbuildHost:" + buildHost;
    //buildTime
    let buildTime: string = deviceInfo.buildTime;
    infoStr += "\nbuildTime:" + buildTime;
    //buildRootHash
    let buildRootHash: string = deviceInfo.buildRootHash;
    infoStr += "\nbuildRootHash:" + buildRootHash;
    //udid
    let udid: string = deviceInfo.udid;
    infoStr += "\nudid:" + udid;
    //distributionOS
    let distributionOS: string = deviceInfo.distributionOSName
    infoStr += "\ndistributionOS:" + distributionOS;
    //distributionOSVersion
    let distributionOSVersion: string = deviceInfo.distributionOSVersion
    infoStr += "\ndistributionOSVersion:" + distributionOSVersion;
    //distributionOSApiVersion
    let distributionOSApiVersion: number = deviceInfo.distributionOSApiVersion
    infoStr += "\ndistributionOSApiVersion:" + distributionOSApiVersion;
    //distributionOSReleaseType
    let distributionOSReleaseType: string = deviceInfo.distributionOSReleaseType
    infoStr += "\ndistributionOSReleaseType号:" + distributionOSReleaseType;
    //odid
    let odid: string = deviceInfo.ODID;
    infoStr += "\nodid:" + odid;
    that.message = infoStr
  }

  build() {
    Column() {
      TitleBar({ pageTitle: $pageTitle })
      Button('获取设备信息')
        .buttonItem()
        .onClick(() => this.deviceInfoClick())
      Scroll(this.scroller) {
        Column() {
          Text(this.message).margin(15)
        }
      }
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
  }
}

在这里插入图片描述


http://www.kler.cn/a/372100.html

相关文章:

  • 智驾感知「大破局」!新一轮混战开启
  • 【多时段】含sop的配电网重构【含分布式电源】【已更新视频讲解】
  • 778-批量删除指定文件夹下指定格式文件(包含子孙文件夹下的)
  • Doris 资源软硬限详解
  • C#(事件)2
  • 工业相机镜头选型知识详解
  • 深入浅出梯度下降算法(学习笔记)
  • xlnt加载excel报错:‘localSheetId‘ expected
  • springboot日志配置
  • 力扣算法笔记——生成随机数组
  • 从单体架构到云原生架构演化图示
  • M1 Pro MacBook Pro 上的奇遇:Rust 构建失败,SIGKILL 惊魂记
  • 「C/C++」C++17 之 std::variant 安全的联合体(变体)
  • 【FinalShell问题】FinalShell连接虚拟机超时问题
  • Javaweb项目发布到阿里云服务器
  • MongoDB 部署指南:从 Linux 到 Docker 的全面讲解
  • AUTOSAT-PDUR模块
  • 【Linux】 su 和 sudo 的区别剖析
  • B计划在哪里?下一个10年我在哪里?
  • 基于uniapp微信小程序的餐厅预约点餐系统
  • NORDIC NPM1300是一款高度集成的电源管理集成电路
  • 封闭空间防碰撞无人机技术详解
  • ROC 曲线:医学研究中的得力助手
  • 操作系统学习笔记-2.3哲学家和管程问题
  • MaxKB: 一款基于大语言模型的知识库问答系统
  • WPF拖拽交互全攻略及实现自定义拖拽控件及数据交换技巧解析