如何获取Android设备实际上下行网速及实现APP日流量统计?
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:
- Fetch initial cumulative bytes when your app starts:
Note: A return value ofvar initialRxBytes = TrafficStats.getTotalRxBytes() // Total received bytes since device boot var initialTxBytes = TrafficStats.getTotalTxBytes() // Total sent bytes since device boot-1means the device doesn't support this metric—add fallback logic (like showing "Unavailable") for such cases. - 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 } } - Permissions: Add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />to yourAndroidManifest.xml—this is required to access basic network stats on most Android versions.
- Fetch initial cumulative bytes when your app starts:
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
SinceTrafficStatsreturns data from device boot, you need to store daily baselines to calculate daily usage:- 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)
- 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.
- Use Room Database (recommended for structured data) or SharedPreferences to save:
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.
- Add
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_STATSpermission, plusACCESS_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
-1forTrafficStatsvalues, and show clear messages if permissions are denied.
内容的提问来源于stack exchange,提问作者Rushikesh Koli

