HarmonyOS 有网络接口支持同时使用wifi和移动流量吗?然后自动识别切换

HarmonyOS
21h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

关于网络连接这块,以下demo是有实现识别网络并切换的能力

import { BusinessError } from '@kit.BasicServicesKit';
import { connection } from '@kit.NetworkKit';
import { HashMap } from '@kit.ArkTS';
import { radio } from '@kit.TelephonyKit';

@Entry
@Component
struct Index {
  private tag: string = 'NetStatusListen';
  private netCon: connection.NetConnection = connection.createNetConnection();
  @State netAvailable: boolean = true;
  @State netBearType: number = -1;
  @State signalTypeName: string = '';
  @State signalLevelName: number = 0;
  private netBearHashMap: HashMap<number, string> = new HashMap();
  private signalTypeHashMap: HashMap<string, string> = new HashMap();
  @State slotId: number = 0;

  aboutToAppear(): void {
    this.init()

    this.onNetCapabilitiesChange()
  }

  init() {
    // 网络类型
    this.netBearHashMap.set(0, '蜂窝网络')
    this.netBearHashMap.set(1, 'Wi-Fi网络')
    this.netBearHashMap.set(2, '以太网网络')

    // 蜂窝类型
    this.signalTypeHashMap.set('0', '未知网络类型')
    this.signalTypeHashMap.set('1', 'GSM')
    this.signalTypeHashMap.set('2', 'CDMA')
    this.signalTypeHashMap.set('3', 'WCDMA')
    this.signalTypeHashMap.set('4', 'TDSCDMA')
    this.signalTypeHashMap.set('5', 'LTE')
    this.signalTypeHashMap.set('6', 'NR')
  }

  build() {
    Column({ space: 15 }) {
      Row() {
        Text('网络开关')
          .textStyle()
        Blank()
        Toggle({ type: ToggleType.Switch, isOn: this.netAvailable })
          .height(24)
          .enabled(false)
      }
      .itemStyle()

      Text('网络类型:' + this.netBearTypeNameMapping(this.netBearType))
        .itemStyle()

      if (this.netBearType == 0) {
        Text('SIM卡槽:' + `${this.slotId == 0 ? 'SIM卡1' : 'SIM卡2'}`)
          .itemStyle()

        Text('蜂窝网络类型:' + this.signalTypeName)
          .itemStyle()

        Text('信号强度等级:' + this.signalLevelName)
          .itemStyle()
      }
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .backgroundColor($r('app.color.light_gray'))
  }

  getSignalInformation() {
    // 获取蜂窝网络的SIM卡槽
    radio.getPrimarySlotId((err: BusinessError, data: number) => {
      if (err) {
        console.error(this.tag, `getPrimarySlotId failed, callback: err->${JSON.stringify(err)}`);
        return;
      }
      console.log(this.tag, `getPrimarySlotId success, callback: data->${JSON.stringify(data)}`);
      this.slotId = data;
      radio.getSignalInformation(data, (err: BusinessError, data: Array<radio.SignalInformation>) => {
        if (err) {
          console.error(this.tag, `getSignalInformation failed, callback: err->${JSON.stringify(err)}`);
          return;
        }
        console.log(this.tag, `getSignalInformation success, callback: data->${JSON.stringify(data)}`);
        if (data) {
          this.signalTypeName = this.signalTypeHashMap.get(data[0].signalType.toString())
          this.signalLevelName = data[0].signalLevel
        }
      });
    });
  }

  onNetCapabilitiesChange() {
    // 先使用register接口注册订阅事件
    this.netCon.register((error: BusinessError) => {
      if (error) {
        console.log(this.tag, `register failed ` + JSON.stringify(error));
      } else {
        console.log(this.tag, `register success`);
      }
    });

    // 订阅网络可用事件。调用register后,才能接收到此事件通知
    this.netCon.on('netAvailable', (data: connection.NetHandle) => {
      console.log(this.tag, 'netAvailable' + JSON.stringify(data));
      this.netAvailable = true;
      connection.getNetCapabilities(data, (error: BusinessError, data: connection.NetCapabilities) => {
        if (error) {
          console.log(this.tag, 'getNetCapabilities ' + JSON.stringify(error));
        }

        console.log(this.tag, 'getNetCapabilities ' + JSON.stringify(data));
        // 解析网络类型
        if (data && data.bearerTypes) {
          this.netBearType = data.bearerTypes[0];
          if (data.bearerTypes[0] == 0) {
            this.getSignalInformation()
          }
        }
      })
    });

    // 订阅网络能力变化事件
    this.netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
      console.log(this.tag, 'netCapabilitiesChange' + JSON.stringify(data));
    });

    // 订阅网络可用事件
    this.netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
      console.log(this.tag, 'netConnectionPropertiesChange' + JSON.stringify(data));
    });

    // 订阅网络丢失事件
    this.netCon.on('netLost', (data: connection.NetHandle) => {
      console.log(this.tag, 'netLost' + JSON.stringify(data));
      this.netAvailable = false;
    });

    // 订阅网络不可用事件。调用register后,才能接收到此事件通知
    this.netCon.on('netUnavailable', () => {
      console.log(this.tag, 'netUnavailable');
      this.netAvailable = false;
    });
  }

  netBearTypeNameMapping(netBearType: number) {
    if (!this.netAvailable) {
      this.netBearType = -1;
      return "网络未开启"
    }
    return this.netBearHashMap.get(netBearType) ? this.netBearHashMap.get(netBearType) : '未知'
  }
}

@Extend(Text)
function textStyle() {
  .fontColor($r('app.color.text_normal'))
  .fontWeight(400)
  .fontFamily('HarmonyHeiTi')
  .fontSize(16)
}

@Styles
function itemStyle() {
  .width('100%')
  .height(56)
  .padding({ left: 12, right: 12 })
  .backgroundColor(Color.White)
  .borderRadius(12)
}
分享
微博
QQ
微信
回复
20h前
相关问题
如何判断应用使用流量网络wifi
589浏览 • 1回复 待解决
如何判断移动流量热点网络
1766浏览 • 1回复 待解决
WebView支持流量模式
697浏览 • 1回复 待解决
Lite Wearable 不支持 http 网络接口
3545浏览 • 1回复 待解决
HI3861 wifi模组能同时支持sta+ap?
9782浏览 • 2回复 待解决
HarmonyOS 相机同时支持拍照录像
135浏览 • 1回复 待解决
ArkTS语言支持语音识别?
1127浏览 • 1回复 待解决
HarmonyOS 自动连接wifi的功能
146浏览 • 1回复 待解决
办法连接隐藏SSID的wifi
821浏览 • 1回复 待解决
HarmonyOS 新平台能否给与流量支持
152浏览 • 1回复 待解决