当两者都启用时,如何使用数据连接而不是WIFI? [英] How to use data connection instead of WIFI when both are enabled?

查看:133
本文介绍了当两者都启用时,如何使用数据连接而不是WIFI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时启用wifi和数据连接. 由于我需要使用移动数据向移动运营商发送http请求以获取电话号码,但是android会像以前一样使用wifi,所以我该如何使用数据连接代替WIFI?

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?

当我在设备上启用wifi和移动数据时.我使用getAllNetworks()方法,但它始终返回wifi.我不知道为什么在启用wifi和移动数据的同时getAllNetworks仅返回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?

当我只启用移动数据时,getAllNetworks()返回移动数据信息.

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]);
          }
     }
}

在同时启用wifi和数据连接的情况下,有人知道如何使用数据连接而不是WIFI吗?

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

推荐答案

只有在使用Android Lollipop时,才可以使用数据连接而不是WIFI.

You can use data connection instead of WIFI only if you are working on Android Lollipop.

似乎您正在尝试将Android Lollipop与目标API 23一起使用,因为您使用的是bindProcessToNetwork而不是setProcessDefaultNetwork.

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

Android Lollipop允许多网络连接.

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
    }
});

这篇关于当两者都启用时,如何使用数据连接而不是WIFI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆