You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Android设备实际上下行网速及实现APP日流量统计?

Android Network Monitor App: Real-Time Speed & Per-App Daily Traffic Implementation

Hey there! Let's break down how to build those two core features for your Android network monitor app—real-time upload/download speed tracking and per-app daily traffic stats. Since you've already got the framework and design sorted, here's the hands-on implementation details you need:

1. Real-Time Upload/Download Speed Tracking

The key here is leveraging Android's built-in TrafficStats class to get cumulative network data, then calculating the difference over time to get real-time speed.

  • Core Approach:
    1. Fetch initial cumulative bytes when your app starts:
      var initialRxBytes = TrafficStats.getTotalRxBytes() // Total received bytes since device boot
      var initialTxBytes = TrafficStats.getTotalTxBytes() // Total sent bytes since device boot
      
      Note: A return value of -1 means the device doesn't support this metric—add fallback logic (like showing "Unavailable") for such cases.
    2. Use a repeating task (Coroutine, Handler, or WorkManager) to fetch the latest bytes at fixed intervals (e.g., 1 second) and compute speed:
      // Example with Coroutines (ideal for lifecycle-aware apps)
      viewModelScope.launch {
          while (isActive) {
              delay(1000)
              val currentRxBytes = TrafficStats.getTotalRxBytes()
              val currentTxBytes = TrafficStats.getTotalTxBytes()
              
              // Convert bytes to KB/s (adjust to MB/s if needed)
              val downloadSpeed = (currentRxBytes - initialRxBytes) / 1024.0
              val uploadSpeed = (currentTxBytes - initialTxBytes) / 1024.0
              
              // Update your UI with the calculated speeds
              updateSpeedUI(downloadSpeed, uploadSpeed)
              
              // Reset initial values for next iteration
              initialRxBytes = currentRxBytes
              initialTxBytes = currentTxBytes
          }
      }
      
    3. Permissions: Add <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> to your AndroidManifest.xml—this is required to access basic network stats on most Android versions.

2. Per-App Daily Traffic Statistics

To track daily data usage per app, you'll pair TrafficStats (or NetworkStatsManager for more granularity) with local storage to track daily baselines.

  • Step 1: Get the App's Unique UID
    Every app has a unique UID—fetch it using the target app's package name:

    fun getAppUid(packageName: String): Int? {
        return try {
            packageManager.getApplicationInfo(packageName, 0).uid
        } catch (e: PackageManager.NameNotFoundException) {
            null // Handle cases where the app isn't installed
        }
    }
    
  • Step 2: Fetch App-Specific Cumulative Traffic
    Use the UID to get total received/sent bytes for the app:

    val targetPackage = "com.example.targetapp"
    val uid = getAppUid(targetPackage)
    uid?.let {
        val appTotalRx = TrafficStats.getUidRxBytes(it)
        val appTotalTx = TrafficStats.getUidTxBytes(it)
    }
    
  • Step 3: Track Daily Usage with Local Storage
    Since TrafficStats returns data from device boot, you need to store daily baselines to calculate daily usage:

    1. Use Room Database (recommended for structured data) or SharedPreferences to save:
      • The UID of each app you're tracking
      • The baseline Rx/Tx bytes at midnight of each day
      • The total daily usage (current bytes - baseline bytes)
    2. Schedule a daily reset task (e.g., with WorkManager) to run at midnight: calculate the day's total usage, save it to storage, then update the baseline to the current cumulative bytes.
  • Permissions:

    • Add <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" /> to your manifest. This is a special permission—you'll need to redirect users to Settings > Apps > Special access > Usage access to enable it manually.
    • For Android 11+, add <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" /> to access package names of other apps.

Bonus: Granular Network Type Tracking (Wi-Fi vs Mobile)

If you want to split stats by network type, use NetworkStatsManager (API 23+):

  • It lets you query traffic per app, per network type (Wi-Fi, cellular), and per time period.
  • Requires the same PACKAGE_USAGE_STATS permission, plus ACCESS_NETWORK_STATE.

Key Practical Notes

  • Foreground Service: To keep tracking speed in the background (especially on Android O+), use a foreground service with a persistent notification—this prevents the system from killing your app.
  • Unit Conversion: Write a helper function to convert raw bytes to user-friendly units (KB/MB/GB) for display.
  • Edge Cases: Gracefully handle devices that return -1 for TrafficStats values, and show clear messages if permissions are denied.

内容的提问来源于stack exchange,提问作者Rushikesh Koli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:00:08