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

How to stay connected through mobile network after WIFI is connected on Android?

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

我希望应用程序继续使用 3G,即使现在也连接了 WIFI。我想这样做以保持连续性。 (用户可能 opt-in/out to/from 这种行为)。

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

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

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

这是执行此操作的步骤,来自 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...

}