HarmonyOS import \{ connection \} from '@kit.NetworkKit'监听不到每次网络连接状态变化?

netConnection.on监听只在进入页面时执行一次,每次关闭wifi打开wifi监听不到状态改变 。

阅读 571
1 个回答

参考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(Color.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("#182431")
  .fontWeight(400)
  .fontFamily('HarmonyHeiTi')
  .fontSize(16)
}

@Styles
function itemStyle() {
  .width('100%')
  .height(56)
  .padding({ left: 12, right: 12 })
  .backgroundColor(Color.White)
  .borderRadius(12)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进