目录

How do I implement priority access to the Wi-Fi network when multiple networks are connected?

Symptom

When using the Video component to load online videos, it is found that the video loading is slow when the Bluetooth network is used, but the Wi-Fi network is fast. Therefore, the Wi-Fi network needs to be used preferentially.

Solution

  1. Apply for the ohos.permission.INTERNET,ohos.permission.GET_NETWORK_INFO permission. In the stage model, declare the permission in the module.json5 configuration file.
    {
      "module": {
        // ...
        "requestPermissions":[
          {
            "name": "ohos.permission.INTERNET",
            "reason": "$string:internet_reason",
            "usedScene": {
              "abilities": [
                "EntryAbility"
              ],
              "when": "inuse"
            }
          },
          {
            "name" : "ohos.permission.GET_NETWORK_INFO",
            "reason": "$string:internet_reason",
            "usedScene": {
              "abilities": [
                "EntryAbility"
              ],
              "when":"inuse"
            }
          },
        ]
      }
    }
  2. Write a Wi-Fi network management class that prioritizes using Wi-Fi.
    // WifiManager.ets
    import { BusinessError } from '@kit.BasicServicesKit';
    import { connection } from '@kit.NetworkKit';
    
    export class WifiManager {
      private static instance?: WifiManager;
    
      /**
       * Get singleton
       *
       * @returns Singleton object
       */
      public static getInstance(): WifiManager {
        if (!WifiManager.instance) {
          WifiManager.instance = new WifiManager();
        }
        return WifiManager.instance;
      }
    
      /**
       * Start listening for network changes (Wi-Fi network / Bluetooth network / cellular data)
       */
      public startListenNetChange(): void {
        console.info("registerNetListener");
        let netConnectionWifi = connection.createNetConnection({
          netCapabilities: {
            bearerTypes: [connection.NetBearType.BEARER_WIFI]
          }
        });
        netConnectionWifi.register((error: BusinessError) => {
          if (error) {
            console.error(`register error: ${error.code}`);
          }
        });
        netConnectionWifi.on('netAvailable', () => {
          console.info("netConnectionWifi netAvailable");
          this.bindWifiWhenConnected();
        });
        netConnectionWifi.on('netLost', () => {
          console.info("Wifi netLost");
          this.bindWifiWhenConnected();
        });
        let netConnectionBluetooth = connection.createNetConnection({
          netCapabilities: {
            bearerTypes: [connection.NetBearType.BEARER_BLUETOOTH]
          }
        });
        netConnectionBluetooth.register((error: BusinessError) => {
          if (error) {
            console.error(`register error: ${error.code}`);
          }
        });
        netConnectionBluetooth.on('netAvailable', () => {
          console.info('netConnectionBluetooth netAvailable');
          this.bindWifiWhenConnected();
        });
        netConnectionBluetooth.on('netLost', () => {
          console.info('Bluetooth netLost');
          this.bindWifiWhenConnected();
        });
        let netConnectionCellular = connection.createNetConnection({
          netCapabilities: {
            bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
          }
        });
        netConnectionCellular.register((error: BusinessError) => {
          if (error) {
            console.error(`register error: ${error.message}`);
          }
        });
        netConnectionCellular.on('netAvailable', () => {
          console.info('netConnectionCellular netAvailable');
          this.bindWifiWhenConnected();
        });
        netConnectionCellular.on('netLost', () => {
          console.info('Cellular netLost');
          this.bindWifiWhenConnected();
        });
      }
    
      /**
       * Connect the App to the Wi-Fi network asynchronously
       */
      private async bindWifiWhenConnected(): Promise<void> {
        await connection.setAppNet(connection.getDefaultNetSync()).then(() => {
          console.info('setAppNet default success')
        });
        connection.getAllNets().then((data: connection.NetHandle[]) => {
          data.forEach(net => {
            connection.getNetCapabilities(net).then((data: connection.NetCapabilities) => {
              if (data.bearerTypes.length > 0 && data.bearerTypes[0] === connection.NetBearType.BEARER_WIFI) {
                connection.setAppNet(net).then(() => {
                  console.info('setAppNet wifi success');
                  return;
                }).catch((error: Error) => {
                  console.error(`setAppNet wifi failed, error = ${error.message}`);
                })
              }
            }).catch((error: Error) => {
              console.error(`getNetCapabilities error = ${error.message}`);
            });
          })
        }).catch((error: Error) => {
          console.error(`getAllNets error = ${error.message}`);
        });
      }
    }
  3. Obtain the instance and call the listening method.
    import { WifiManager } from './WifiManager'
    
    // Register for change monitoring
    WifiManager.getInstance().startListenNetChange();

Reference

connection.createNetConnection

connection.setAppNet

connection.getAllNets

connection.getNetCapabilities