阿里云主机折上折
  • 微信号
Current Site:Index > Running and Debugging (Simulator, Real Device Debugging)

Running and Debugging (Simulator, Real Device Debugging)

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

Running and Debugging (Simulator, Real Device Debugging)

During uni-app development, running and debugging are crucial steps to ensure application quality. Developers need to be familiar with simulator debugging, real device debugging, and the use of related toolchains to efficiently identify and resolve issues.

Simulator Debugging

Simulator debugging is the most commonly used method in the early stages of development, allowing for quick validation of functionality without a physical device. uni-app supports various simulator environments:

  1. HBuilderX Built-in Simulator:

    • Built-in Android simulator with fast startup
    • Supports hot reload, automatically refreshing after code changes
    # Start Android simulator
    npm run dev:android
    
  2. Third-Party Simulators:

    • Recommended: Nox, MuMu, and other mainstream Android simulators
    • iOS development requires Xcode's built-in Simulator
    # iOS simulator run command
    npm run dev:ios
    
  3. Browser Debugging:

    • H5 platform can be debugged directly in Chrome or other browsers
    • Supports Vue Devtools plugin
    // Example: Output logs during debugging
    console.log('Current page path:', this.$route.path);
    

Common issues during simulator debugging:

  • Port conflicts: Modify the devServer port in manifest.json
  • Style anomalies: Check if rpx unit conversion is correct
  • API call failures: Ensure the simulator has proper network connectivity

Real Device Debugging

Real device debugging can uncover issues not reproducible on simulators, especially device-specific behaviors:

  1. Android Real Device Debugging:

    • Enable USB debugging mode
    • Use adb commands to check connection status
    adb devices
    # Example output:
    # List of devices attached
    # 1234567890abcdef device
    
  2. iOS Real Device Debugging:

    • Requires an Apple Developer account
    • Configure the correct Provisioning Profile
    # View device UDID
    idevice_id -l
    
  3. Debugging Tools:

    • Use Android Studio's Logcat for detailed logs
    • Use Safari Developer Tools to debug iOS WebView
    // Device-specific debugging method
    plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
      console.log('App version:', widgetInfo.version);
    });
    

Real device debugging tips:

  • Use the vConsole plugin to enhance mobile log output
  • Test performance specifically on low-end devices
  • Be mindful of compatibility issues across different manufacturer systems

Cross-Platform Debugging Strategies

uni-app's multi-platform nature requires targeted debugging methods:

  1. Conditional Compilation Debugging:

    // #ifdef H5
    console.log('Currently running on H5 platform');
    // #endif
    
    // #ifdef APP-PLUS
    console.log('Currently running on App platform');
    // #endif
    
  2. Platform-Specific Issue Handling:

    • Pay attention to routing differences on H5
    • Handle native plugin compatibility on App
    • Note API permission restrictions on mini-programs
  3. Performance Debugging Tools:

    • Use Chrome Performance panel to analyze H5 performance
    • Monitor native layer memory usage with Android Profiler
    // Performance monitoring example
    console.time('renderTime');
    // ...Execute code
    console.timeEnd('renderTime');
    

Advanced Debugging Techniques

  1. Remote Debugging:

    • Use Weinre for remote debugging of mobile devices
    • Configure reverse proxies to resolve development environment API issues
  2. Exception Capture:

    // Global error capture
    uni.onError((err) => {
      console.error('Global exception:', err);
      uni.reportAnalytics('error', {msg: err.message});
    });
    
  3. Custom Debug Panel:

    <template>
      <view v-if="isDebug" class="debug-panel">
        <text>FPS: {{fps}}</text>
        <button @click="showLogs">Show Logs</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {
          isDebug: process.env.NODE_ENV === 'development',
          fps: 0
        }
      },
      methods: {
        calculateFPS() {
          // FPS calculation logic
        }
      }
    }
    </script>
    

Debugging Environment Configuration

  1. Environment Variable Management:

    // config.js
    module.exports = {
      development: {
        API_BASE: 'http://dev.example.com'
      },
      production: {
        API_BASE: 'https://api.example.com'
      }
    }
    
  2. Mock Data Configuration:

    // mock/user.js
    module.exports = {
      'GET /api/user': {
        code: 200,
        data: {name: 'Mock User'}
      }
    }
    
  3. Continuous Integration Debugging:

    • Configure automated test scripts
    • Integrate CI tools like Jenkins for automatic test builds

Common Issue Troubleshooting

  1. White Screen Issues:

    • Check if routing configuration is correct
    • Verify if global error handling was triggered
  2. Native Plugin Failures:

    # Reinstall plugin
    npm install native-plugin --save
    
  3. Style Anomalies:

    • Check if the scoped attribute is missing
    • Validate CSS preprocessor configuration
  4. API Response Anomalies:

    // Example: Network request debugging
    uni.request({
      url: 'https://api.example.com/data',
      success: (res) => {
        console.debug('Response data:', res.data);
      },
      fail: (err) => {
        console.error('Request failed:', err.errMsg);
      }
    });
    

Debugging Tool Integration

  1. HBuilderX Debugging Features:

    • Breakpoint debugging
    • Real-time log output
    • Memory analysis tools
  2. Third-Party Toolchains:

    • Charles packet capture tool configuration
    # Configure proxy
    adb reverse tcp:8888 tcp:8888
    
  3. Custom Logging System:

    const logger = {
      info(msg) {
        console.log(`[INFO] ${new Date().toISOString()}: ${msg}`);
      },
      error(msg) {
        console.error(`[ERROR] ${new Date().toISOString()}: ${msg}`);
      }
    };
    

Multi-Device Synchronized Testing

  1. Device Farm Usage:

    • Configure multi-device parallel testing
    • Use automated test scripts
  2. Cloud Testing Platforms:

    • Integrate cloud testing services like Sauce Labs
    • Generate cross-device test reports
  3. Differentiation Handling:

    // Device feature detection
    const isHighEndDevice = plus.device.vendor === 'apple' || 
                          (plus.device.vendor === 'android' && plus.device.memory > 2048);
    

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.