HarmonyOS 网络变化监听失效?

import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

export class SNMDemo {
  constructor() {
    this.init();
  }

  init() {
    console.info('init start');
    let netSpecifier: connection.NetSpecifier = {
      netCapabilities: {
        bearerTypes: [connection.NetBearType.BEARER_CELLULAR, connection.NetBearType.BEARER_WIFI,
          connection.NetBearType.BEARER_ETHERNET],
        // 指定网络能力为Internet
        networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
      },
    };

    // 指定超时时间为10s(默认值为0)
    let timeout = 10 * 1000;

    // 创建NetConnection对象
    let conn = connection.createNetConnection(netSpecifier, timeout);

    // 订阅指定网络状态变化的通知
    conn.register((err: BusinessError, data: void) => {
      if (err) {
        console.error(`监听网络状态失败 ${JSON.stringify(err)}`)
      }
    });

    // 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户
    conn.on('netAvailable', ((data: connection.NetHandle) => {
      console.info(`netAvailable ${data.netId}`);
      connection.getNetCapabilities(data, (error, data) => {
        if (error) {
          console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`)
          return;
        }
        const netType = [...data.bearerTypes].sort().join(',');
        console.info(`netAvailable type change ${netType}`);
      })
    }));

    // 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户
    conn.on('netUnavailable', ((data: void) => {
      console.info(`netUnavailable`);
    }));
    console.info(`init end`);
  }
}

之后在页面中创建

@Entry
@Component
struct Index {
  private demo = new SNMDemo();
}

目前只有刚创建的netAvailable回调,之后关闭打开wifi、移动网络没有任何回调触发。

阅读 495
1 个回答

请参考示例如下修改,关闭网络监听用netLost:

import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let netSpecifier: connection.NetSpecifier = {
  netCapabilities: {
    bearerTypes: [connection.NetBearType.BEARER_CELLULAR, connection.NetBearType.BEARER_WIFI,
      connection.NetBearType.BEARER_ETHERNET],
    // 指定网络能力为Internet
    networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
  },
};
// 指定超时时间为10s(默认值为0)
let timeout = 10 * 1000;
// 创建NetConnection对象
let conn = connection.createNetConnection(netSpecifier, timeout);

// netCon: connection.NetConnection = connection.createNetConnection();
export class SNMDemo {
  init() {
    console.info('init start');
    // let netSpecifier: connection.NetSpecifier = {
    // netCapabilities: {
    // bearerTypes: [connection.NetBearType.BEARER_CELLULAR, connection.NetBearType.BEARER_WIFI,
    // connection.NetBearType.BEARER_ETHERNET],
    // // 指定网络能力为Internet
    // networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
    // },
    // };
    // // 指定超时时间为10s(默认值为0)
    // let timeout = 10 * 1000;
    // // 创建NetConnection对象
    // let conn = connection.createNetConnection(netSpecifier, timeout);

    // 订阅指定网络状态变化的通知
    conn.register((err: BusinessError, data: void) => {
      if (err) {
        console.error(`监听网络状态失败 ${JSON.stringify(err)}`)
      }
    });
    // 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户
    conn.on('netAvailable', ((data: connection.NetHandle) => {
      console.info(`netAvailable ${data.netId}`);
      connection.getNetCapabilities(data, (error, data) => {
        if (error) {
          console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`)
          return;
        }
        const netType = [...data.bearerTypes].sort().join(',');
        console.info(`netAvailable type change ${netType}`);
      })
    }));
    // 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户
    conn.on('netUnavailable', ((data: void) => {
      console.info(`netUnavailable`);
    }));
    // 订阅网络可用事件。调用register后,才能接收到此事件通知
    conn.on('netLost', (data: connection.NetHandle) => {
      console.log("lose----", JSON.stringify(data));
    });
    console.info(`init end`);
  }
}

export const defaultInstance = new SNMDemo();
logo
HarmonyOS
子站问答
访问
宣传栏