How to access data usage settings of specific app programmatically?

不想你离开。 提交于 2019-12-04 06:53:13

问题


I'm developing an Android app which needs to download a lot of data.

I'd like to measure the data traffic of my app for specific period of time (like month).

This option is available on System Settings -> Data Usage.

  1. Is there any way to access this setting programmatically?
  2. Can I use some of android libs to get traffic?

I know about TrafficStats class but I can not get traffic for specific period of time and when i boot device this data is lost.


回答1:


  1. Is there any way to access this setting programmatically?

try these code below:

public boolean invokeMethod(String methodName, Object[] args) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[] argsClass = null;
    if (args != null) {
        argsClass = new Class[1];
        argsClass[0] = args.getClass();
    }
    Method method = ownerClass.getMethod(methodName, argsClass);
    return (Boolean)method.invoke(mcm, args);
}

public Object invokeBooleanArgMethod(String methodName, boolean value) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[]  argsClass = new Class[1];
    argsClass[0] = boolean.class;
    Method method = ownerClass.getMethod(methodName,argsClass);
    return method.invoke(mcm, value);
}

/* use these two method like these */
Object[] arg = null;
try {
    boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled", arg);
    if(!isMobileDataEnable){
        invokeBooleanArgMethod("setMobileDataEnabled", true);
    }
} catch (Exception e) {
    e.printStackTrace();
}

Also, in AndroidManifest.xml, you need to add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
  1. Can I use some of android libs to get traffic?

You can set an alarm or thread in service to get traffic periodically with TrafficStats for all process. If you want to get traffic of each process, I think you can see this answer.



来源:https://stackoverflow.com/questions/25499918/how-to-access-data-usage-settings-of-specific-app-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!