gpt4 book ai didi

android - Android连接WIFI后如何通过移动网络保持连接?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:08 27 4
gpt4 key购买 nike

我注意到,当通过 3G(移动)连接从远程服务器流式传输音频时,当 WIFI 断开或关闭时,一旦 WIFI 被激活并连接,通过 3G 的连接就会断开。

我希望应用程序继续使用 3G,即使现在也连接了 WIFI。我想这样做以保持连续性。 (用户可以选择加入/退出此行为)。

是否有专门的标志、锁等。为此目的?

最佳答案

这在 Android 5.0 (Lollipop) 之前的设备上是不可能的。操作系统一次只能保持一个接口(interface),应用程序无法控制这一选择。

在运行 Android 5.0 或更高版本的设备上,您可以使用新的多网络 API 来选择要用于网络流量的接口(interface)。

这是执行此操作的步骤,来自 Android 5.0 changelog :

To select and connect to a network dynamically from your app, follow these steps:

  1. Create a ConnectivityManager.
  2. Use the NetworkRequest.Builder class to create an NetworkRequest object and specify the network features and transport type your app is interested in.
  3. To scan for suitable networks, call requestNetwork() or registerNetworkCallback(), and pass in the NetworkRequest object and an implementation of ConnectivityManager.NetworkCallback. Use the requestNetwork() method if you want to actively switch to a suitable network once it’s detected; to receive only notifications for scanned networks without actively switching, use the registerNetworkCallback() method instead.

When the system detects a suitable network, it connects to the network and invokes the onAvailable() callback. You can use the Network object from the callback to get additional information about the network, or to direct traffic to use the selected network.

具体来说,如果您想强制通过 3G/LTE 传输流量,即使存在 WiFi 信号,您也可以使用如下方式:

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder req = new NetworkRequest.Builder();
req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {

@Override
public void onAvailable(Network network) {
// If you want to use a raw socket...
network.bindSocket(...);
// Or if you want a managed URL connection...
URLConnection conn = network.openConnection(...);
}

// Be sure to override other options in NetworkCallback() too...

}

关于android - Android连接WIFI后如何通过移动网络保持连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com