How to disable mobile data programmatically only for my application

I am developing an application, and I am concerned about the amount of data that users can transfer among themselves. Since some users have limited mobile data plans and some do not, I would like to know if I can develop a switch to turn off mobile data for my specific application. It’s a bit like Android uses its own data usage -> mobile -> App -> "Limit source data" ...

he says (and does) that he "disables the original data only for the mobile data network. Wi-Fi will be used if it is available." I want this, but not only in the background.

I know that I can’t change the “Limit source data” setting, as this will make it useless if the applications can untie it ... but is there a way by which I can programmatically say that now my application blocks access to mobile data, now is it not?

as an understanding of why I want this, I try not to cause remote access calls when the user selects this option (which I did and works), but there are some data leaks (some kbs per day) that I can't seem to block. .. either because the system supports http connections, or some other unclear reason ...

I see these data transfers in the DDMS perspective on eclipse in the network statistics for my application.

Thanks for any help

+4
2

, wifi , wifi, .

, .

, Wi-Fi Android?

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

AndroidManifest.manifest, .

+1

moblie: -

Java-

private void setMobileDataEnabled(Context context, boolean enabled) {
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
0

Source: https://habr.com/ru/post/1546146/


All Articles