Tuesday, June 13, 2023

How to Measure Data Usage for Each App on Android Using Kotlin

Measuring Data Usage for Each Package on a Phone Using Kotlin

This article explains how to measure data usage for each package on a phone using a function written in Kotlin. The function, getEachPackageUsage, takes the package name (packageName), network type (networkType), start time (startTime), and end time (endTime) as input.

Function Definition


private fun getEachPackageUsage(
    packageName: String,
    networkType: Int,
    startTime: Long,
    endTime: Long
): Long {
    // Write code
}

First, use the PackageManager's getInstalledApplications() function to get a list of installed applications. Then, find the UID of the application with the specified package name.


val uid = AgentApp.instance.packageManager.getInstalledApplications(0)
    .find { app -> app.packageName.contains(packageName) }?.uid

Use the NetworkStatsManager object to get network statistics data. When doing so, pass the networkType, startTime, endTime, and uid values.


val networkStats = nsm.queryDetailsForUid(networkType, null, startTime, endTime, uid ?: -1)

Use the received network statistics values to sum up the data usage. When doing so, add both txBytes (sent data) and rxBytes (received data).


var total = 0L
while (networkStats.hasNextBucket()) {
    val entry = NetworkStats.Bucket()
    networkStats.getNextBucket(entry)

    if (entry.uid == uid) {
        total += entry.txBytes
        total += entry.rxBytes
    }
}

Once the process is complete, close networkStats.


networkStats.close()

Convert the data usage to megabytes (MB) and return it.


return total / 0x0100000 //MB conversion

Completed Code

As a result, the completed code is as follows:


private fun getEachPackageUsage(
    packageName: String,
    networkType: Int,
    startTime: Long,
    endTime: Long
): Long {
    val uid = AgentApp.instance.packageManager.getInstalledApplications(0)
        .find { app -> app.packageName.contains(packageName) }?.uid
    val networkStats = nsm.queryDetailsForUid(networkType, null, startTime, endTime, uid ?: -1)
    var total = 0L
    while (networkStats.hasNextBucket()) {
        val entry = NetworkStats.Bucket()
        networkStats.getNextBucket(entry)

        if (entry.uid == uid) {
            total += entry.txBytes
            total += entry.rxBytes
        }
    }
    networkStats.close()
    return total / 0x0100000 //MB conversion
}

As such, we have learned how to measure and manage data usage for each package on a phone using the getEachPackageUsage function. This will allow users to more clearly understand their data usage.


0 개의 댓글:

Post a Comment