阿里云主机折上折
  • 微信号
Current Site:Index > Get device information (uni.getSystemInfo)

Get device information (uni.getSystemInfo)

Author:Chuan Chen 阅读数:13959人阅读 分类: uni-app

Basic Concept of uni.getSystemInfo

uni.getSystemInfo is a native API provided by uni-app for obtaining device information of the current runtime environment. This API returns a Promise object containing detailed information such as device model, operating system version, screen dimensions, window dimensions, pixel ratio, etc. Developers can use this information for responsive layouts, device adaptation, or feature detection.

uni.getSystemInfo({
  success: (res) => {
    console.log(res);
  },
  fail: (err) => {
    console.error(err);
  }
});

Detailed Explanation of Return Parameters

The object returned by uni.getSystemInfo includes the following main properties:

  • brand: Device brand (e.g., Apple, Huawei)
  • model: Device model (e.g., iPhone X)
  • pixelRatio: Device pixel ratio
  • screenWidth/screenHeight: Screen width and height (in px)
  • windowWidth/windowHeight: Usable window width and height (in px)
  • statusBarHeight: Status bar height (in px)
  • platform: Runtime platform (ios/android)
  • system: Operating system version
  • language: System language
  • version: Base library version
  • fontSizeSetting: User-set font size
  • SDKVersion: Mini-program SDK version
// Example of obtaining device information
uni.getSystemInfo({
  success: (res) => {
    this.deviceInfo = {
      model: res.model,
      system: res.system,
      screenWidth: res.screenWidth,
      screenHeight: res.screenHeight
    };
  }
});

Practical Application Scenarios

Responsive Layout Adaptation

Adjust layouts dynamically based on device screen dimensions:

data() {
  return {
    isSmallScreen: false
  }
},
onLoad() {
  uni.getSystemInfo({
    success: (res) => {
      this.isSmallScreen = res.screenWidth < 375;
    }
  });
}

Platform-Specific Feature Implementation

Implement differentiated features for different platforms:

uni.getSystemInfo({
  success: (res) => {
    if (res.platform === 'ios') {
      this.setupIOSFeatures();
    } else if (res.platform === 'android') {
      this.setupAndroidFeatures();
    }
  }
});

Safe Area Handling

Handle the bottom safe area for devices like iPhone X:

computed: {
  safeAreaBottom() {
    const info = this.deviceInfo;
    if (info.model.includes('iPhone X')) {
      return '34px';
    }
    return '0px';
  }
}

Synchronous Retrieval Method

uni-app also provides a synchronous API for obtaining device information:

try {
  const res = uni.getSystemInfoSync();
  console.log(res.windowWidth);
} catch (e) {
  console.error(e);
}

Performance Optimization Recommendations

  1. Cache Device Information: Avoid repeated calls
  2. Fetch on Demand: Only retrieve necessary properties
  3. Use Synchronous Methods Wisely: Use synchronous methods in performance-sensitive scenarios
// Example of caching device information
let cachedSystemInfo = null;

function getSystemInfo() {
  if (!cachedSystemInfo) {
    cachedSystemInfo = uni.getSystemInfoSync();
  }
  return cachedSystemInfo;
}

Common Issue Solutions

Incorrect Window Height Retrieval

uni.getSystemInfo({
  success: (res) => {
    // Account for navigation bar and status bar
    const usableHeight = res.windowHeight - res.statusBarHeight - 44;
    this.contentHeight = usableHeight + 'px';
  }
});

Handling Different Pixel Ratios

uni.getSystemInfo({
  success: (res) => {
    // Convert design dimensions to actual pixels
    const scale = res.pixelRatio;
    this.realWidth = designWidth * scale;
  }
});

Advanced Usage

Monitoring Device Changes

// Listen for screen rotation
onShow() {
  this.orientationListener = () => {
    uni.getSystemInfo({
      success: (res) => {
        this.handleOrientationChange(res);
      }
    });
  };
  window.addEventListener('resize', this.orientationListener);
},
onHide() {
  window.removeEventListener('resize', this.orientationListener);
}

Using with CSS Variables

uni.getSystemInfo({
  success: (res) => {
    document.documentElement.style.setProperty('--status-bar-height', `${res.statusBarHeight}px`);
    document.documentElement.style.setProperty('--window-height', `${res.windowHeight}px`);
  }
});

Cross-Platform Compatibility Handling

Handle differences across platforms:

function getSafeArea() {
  const info = uni.getSystemInfoSync();
  let safeArea = { top: 0, bottom: 0 };
  
  // iOS handling
  if (info.platform === 'ios') {
    safeArea.top = info.statusBarHeight;
    if (info.model.match(/iPhone X|iPhone 11|iPhone 12/)) {
      safeArea.bottom = 34;
    }
  }
  
  // Android handling
  if (info.platform === 'android' && info.screenHeight / info.screenWidth > 1.8) {
    safeArea.bottom = 48;
  }
  
  return safeArea;
}

Comprehensive Application in Real Projects

An example of a complete device information handling module:

// device.js
const device = {
  info: null,
  
  init() {
    if (!this.info) {
      this.info = uni.getSystemInfoSync();
    }
    return this.info;
  },
  
  isIOS() {
    return this.init().platform === 'ios';
  },
  
  isAndroid() {
    return this.init().platform === 'android';
  },
  
  isSmallScreen() {
    return this.init().screenWidth < 375;
  },
  
  isLargeScreen() {
    return this.init().screenWidth >= 414;
  },
  
  getSafeArea() {
    const info = this.init();
    // ...Safe area calculation logic
  }
};

export default device;

Debugging Tips

Debugging device information during development:

// Display device information in a page
<template>
  <view>
    <text v-for="(value, key) in deviceInfo" :key="key">
      {{key}}: {{value}}
    </text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      deviceInfo: {}
    }
  },
  onLoad() {
    uni.getSystemInfo({
      success: (res) => {
        this.deviceInfo = res;
      }
    });
  }
}
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.