How to use data connection instead of WIFI when both are enabled?

拈花ヽ惹草 提交于 2019-12-03 18:45:51

问题


Both wifi and data connection are enabled. Since I need to use mobile data to send a http request to mobile carrier to get phone number, But android will use wifi as prior, so How can I use data connection instead of WIFI?

When I enable the wifi and mobile data int the device. I use getAllNetworks() method, but it always returns wifi. I don't know Why getAllNetworks just return wifi when I enable both wifi and mobile data?

When I just enable the mobile data, the getAllNetworks() return mobile data info.

ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] network = connectivityManager.getAllNetworks();
if(network != null && network.length >0 ){
     for(int i = 0 ; i < network.length ; i++){
          NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network[i]);
          int networkType = networkInfo.getType();
          if(ConnectivityManager.TYPE_MOBILE == networkType ){
               connectivityManager.bindProcessToNetwork(network[i]);
          }
     }
}

Does some one know how to use data connection instead of WIFI when both wifi and data connection are enabled?


回答1:


I worked on this too, and actually you can use data connection instead of WIFI only if you are working on Android Lollipop.

And it seems you are trying to use Android Lollipop with target API 23 because you used bindProcessToNetwork instead of setProcessDefaultNetwork.

Android Lollipop allows the multi-network connection.

ConnectivityManager cm;
    cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder req = new NetworkRequest.Builder();
    req.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
              //here you can use bindProcessToNetwork
        }

    });

I was looking for this too so I hope this is helpful!




回答2:


Find detailed 4.4 minus design and lollipop and plus design here.

Send request over Mobile data when WIFI is ON.(Android L)



来源:https://stackoverflow.com/questions/32419605/how-to-use-data-connection-instead-of-wifi-when-both-are-enabled

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