简体   繁体   中英

How to turn off LTE data connection programmatically in android 6 and android 7?

I want to reach a router this way:

isReachable = InetAddress.getByName("192.168.1.1").isReachable(2000);

But it returns false.

Curiously when I turn off LTE data manually it works.

I found this code to turn on/off LTE data programmatically but it does not work on android 6 or 7.

private void setMobileDataEnabled(Context context, boolean enabled) 
{
    final ConnectivityManager conman = (ConnectivityManager)    
    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 Class iConnectivityManagerClass =  
    Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = 
    iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", 
    Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);
    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}

Could you help to find an other way to turn on/off LTE data on android 6 or 7?

I found how to resolve my problem. i fail to turn off cellular data programmatically, but if found a way to force my app to use only wifi connection . this is the code:

final ConnectivityManager connectivityManager  = 
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

 NetworkRequest.Builder request = null;
  if (android.os.Build.VERSION.SDK_INT >=                                          
android.os.Build.VERSION_CODES.LOLLIPOP) {
        request = new NetworkRequest.Builder();

        request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

        connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {
            //if (SDK_INT >= LOLLIPOP && SDK_INT <= M) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ConnectivityManager.setProcessDefaultNetwork(network);
            }

            }
    });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM