androidtelephonymanagerandroid-data-usagenetworkstatsmanagerandroid-10.0

Get mobile data usage in Android 10


I'm trying to make a network usage monitor app, which shows mobile data usage history to the user. For this I'm using Usage access to get accurate data usage stats from NetworkStatsManager. But this no longer works in Android 10.

I'm using NetworkStatsManager.querySummaryForDevice which requires subscriber Id, which earlier I was able to obtain using TelephonyManager.getSubscriberId.

But the getSubscriberId is now not working in Android 10 as it requires READ_PRIVILEGED_PHONE_STATE which third-party apps cannot have.

Any ideas on how to make it work? I understand the restrictions for getting subscriber Id, but I don't really care about the subscriber Id as long as I get the mobile data usage, for which I have enough permissions.


Solution

  • When calling NetworkStatsManager resolve subscriberId as follows:

    Here is a sample code that should help:

    public static String getSubscriberId() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                return telephonyManager.getSubscriberId();
            } else {
                return null;
            }
        }
    

    Worked for me on Android API Level 29 and Android API Level 26 devices.