常用于网站推广的营销手段是,端游传奇排行榜前十名,做投标的在什么网站找信息,小微企业名录查询官网前言 大家好,今天我们聊一个看似简单、实则至关重要的技术话题——如何获取和利用设备信息。在移动应用开发中,许多令人头疼的适配问题,其根源往往就在设备信息的处理上。今天,我们就来一起聊聊这个话题。 一、系统信息
1.1 同步vs异步
很多人都知道用uni.getSystemInfo(…前言大家好,今天我们聊一个看似简单、实则至关重要的技术话题——如何获取和利用设备信息。在移动应用开发中,许多令人头疼的适配问题,其根源往往就在设备信息的处理上。今天,我们就来一起聊聊这个话题。一、系统信息1.1 同步vs异步很多人都知道用uni.getSystemInfo(),但其实这里有个性能坑:// 不推荐:每次都调异步APIasyncfunctiongetDeviceInfo(){constinfo=awaituni.getSystemInfo()returninfo}// 推荐:同步获取+缓存letcachedInfo=nullfunctiongetSystemInfo(){if(!cachedInfo){// 首次使用同步API,避免Promise开销cachedInfo=uni.getSystemInfoSync()}returncachedInfo}为什么同步更好?无Promise开销,避免微任务队列调度不用await应用启动时就应该获取但同步API有个坑:在极少数情况下可能会阻塞UI。建议:应用启动时用同步运行时变化用异步监听1.2 专业术语解释constsystemInfo=uni.getSystemInfoSync()// 一下6个字段比较重要:constessentialFields={// 1. 设备识别platform:systemInfo.platform,// "android" | "ios" | "web"model:systemInfo.model,// 具体型号,如"iPhone 13 Pro"// 2. 屏幕信息pixelRatio:systemInfo.pixelRatio,// 设备像素比screenWidth:systemInfo.screenWidth,// 物理像素宽度windowWidth:systemInfo.windowWidth,// 可用宽度// 3. 刘海屏-安全区域safeArea:systemInfo.safeArea,// 安全区域坐标statusBarHeight:systemInfo.statusBarHeight// 状态栏高度}特别说明一下pixelRatio这个字段,很多新手会忽略它:像素比的意义:// 根据像素比加载合适图片functiongetImageUrl(baseUrl,pixelRatio){if(pixelRatio=3)return`${baseUrl}@3x.png`if(pixelRatio=2)return`${baseUrl}@2x.png`return`${baseUrl}.png`}// 计算Canvas绘制尺寸functiongetCanvasSize(designSize,pixelRatio){return{width:designSize.width*pixelRatio,height:designSize.height*pixelRatio,styleWidth:designSize.width,styleHeight:designSize.height}}1.3 平台差异处理uni-app号称"一套代码,多端运行",但现实是不同平台确实存在差异:// Platform适配工具类classPlatformAdapter{staticgetStatusBarHeight(){constinfo=uni.getSystemInfoSync()// iOS和Android的状态栏高度if(info.platform==='ios'){// iOS:iPhone X以上有刘海constisNotchScreen=this.isNotchScreen(info)returnisNotchScreen?44:20}elseif(info.platform==='android'){// Android:通常比iOS高,且版本差异大constversion=parseFloat(info.system.split(' ')[1])||0returnversion=10?28:25}return20// Web端默认}staticisNotchScreen(info){// 判断是否为刘海屏constnotchModels=['iPhone X','iPhone 11','iPhone 12','iPhone 13','iPhone 14','iPhone 15']returnnotchModels.some(model=info.model.includes(model))}}二、屏幕适配2.1 rpx单位rpx是uni-app的核心创新,让我们深入了解一下rpx吧。// rpx转换原理functionrpx2px(rpx,windowWidth=375){// 1rpx = windowWidth / 750return(rpx*windowWidth)/750}// 注意事项constdesignWidth=750constdeviceWidth=uni.getSystemInfoSync().windowWidth// 按钮宽度是200rpxconstbuttonDesignWidth=200// 在任何设备上,实际宽度都是:constactualWidth=(buttonDesignWidth/designWidth)*deviceWidthrpx的好处在于:750rpx对应设计稿750px所有元素按屏幕宽度等比缩放框架自动处理转换rpx局限性:不适合需要固定尺寸的场景(如1px边框)在大屏设备上可能过度拉伸图片使用rpx需要配合mode="widthFix"2.2 适配安全区域随着全面屏普及,安全区域适配成了必修课: