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

查看:34
本文介绍了两者都启用时如何使用数据连接而不是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天全站免登陆