引言

App 没网时给个友好提示、网络切换时自动重连、直播时检测弱网降码率——这些能力都靠网络连接诊断。HarmonyOS 的 @ohos.net.connection 模块提供了完整的网络状态监测能力。


一、基础:检测当前网络状态

import connection from '@ohos.net.connection';

1.1 获取网络状态

async function getNetworkState() {
  const netHandle = await connection.getDefaultNet();
  const state = await connection.getNetCapabilities(netHandle);
  
  console.log('网络类型:', state.bearerTypes);    // 例如 [BearerType.CELLULAR]
  console.log('网络能力:', state.networkCapabilities); // 例如 [NET_CAPABILITY_INTERNET]
}

1.2 获取网络类型

// 判断是否有网络
async function isNetworkAvailable(): Promise<boolean> {
  try {
    const netHandle = await connection.getDefaultNet();
    const state = await connection.getNetCapabilities(netHandle);
    return state.bearerTypes.length > 0;
  } catch {
    return false;
  }
}

// 判断当前是 WiFi 还是蜂窝
async function getConnectionType(): Promise<'wifi' | 'cellular' | 'none'> {
  try {
    const netHandle = await connection.getDefaultNet();
    const state = await connection.getNetCapabilities(netHandle);
    
    if (state.bearerTypes.includes(connection.BearerType.WIFI)) return 'wifi';
    if (state.bearerTypes.includes(connection.BearerType.CELLULAR)) return 'cellular';
    return 'none';
  } catch {
    return 'none';
  }
}

二、网络状态实时监听

WiFi断开

网络恢复

质量变化

注册监听

on netCapabilitiesChange

网络变化

切换到蜂窝/显示提示

重试未完成的请求

调整应用行为

2.1 网络能力变化监听

aboutToAppear() {
  connection.on('netCapabilitiesChange', async (netHandle) => {
    const state = await connection.getNetCapabilities(netHandle);
    const hasInternet = state.networkCapabilities.includes(
      connection.NetCap.NET_CAPABILITY_INTERNET
    );
    
    if (hasInternet) {
      this.networkStatus = '已连接';
      this.retryFailedRequests(); // 重试失败的请求
    } else {
      this.networkStatus = '无网络';
      this.showNetworkError();
    }
  });
}

2.2 网络连接/断开监听

// WiFi 连接/断开
connection.on('netAvailable', (netHandle) => {
  console.log('网络可用:', netHandle.netId);
});

connection.on('netLost', (netHandle) => {
  console.log('网络丢失:', netHandle.netId);
});

// 连接状态变化(更细粒度)
connection.on('netStateChange', (data) => {
  console.log('是否WiFi:', data.isWifi);
  console.log('是否蜂窝:', data.isCellular);
  console.log('是否有网络:', data.isAvailable);
});

三、网络地址与 DNS 查询

3.1 获取 IP 地址

async function getLocalIp(): Promise<string[]> {
  const netHandle = await connection.getDefaultNet();
  const addrs = await connection.getAddressesByName(netHandle, 'localhost');
  return addrs.map(a => a.address.address);
}

3.2 DNS 解析

async function dnsLookup(host: string): Promise<string[]> {
  const netHandle = await connection.getDefaultNet();
  const addrs = await connection.getAddressesByName(netHandle, host);
  return addrs.map(a => `${a.address.address}:${a.port}`);
}

// 使用
dnsLookup('api.example.com').then(addrs => {
  console.log('DNS解析结果:', addrs); // ['203.0.113.5:0', '2401:xxxx::1:0']
});

3.3 获取网络代理信息

async function getProxyInfo() {
  const netHandle = await connection.getDefaultNet();
  const proxy = await connection.getDefaultHttpProxy();
  console.log('代理主机:', proxy.host);
  console.log('代理端口:', proxy.port);
  console.log('排除列表:', proxy.exclusionList);
}

四、实战:网络诊断工具

class NetworkDiagnostics {
  private isOnline: boolean = false;
  private currentType: string = 'none';

  async init() {
    try {
      const netHandle = await connection.getDefaultNet();
      const state = await connection.getNetCapabilities(netHandle);
      this.isOnline = state.networkCapabilities.includes(
        connection.NetCap.NET_CAPABILITY_INTERNET
      );
      this.updateType(state);
    } catch {
      this.isOnline = false;
    }
    
    this.startListening();
  }

  private updateType(state: connection.NetCap) {
    if (state.bearerTypes.includes(connection.BearerType.WIFI)) {
      this.currentType = 'WiFi';
    } else if (state.bearerTypes.includes(connection.BearerType.CELLULAR)) {
      this.currentType = '蜂窝网络';
    } else {
      this.currentType = '其他';
    }
  }

  private startListening() {
    connection.on('netCapabilitiesChange', async (handle) => {
      const state = await connection.getNetCapabilities(handle);
      this.isOnline = state.networkCapabilities.includes(
        connection.NetCap.NET_CAPABILITY_INTERNET
      );
      this.updateType(state);
      console.log(`网络更新: ${this.currentType}, 在线: ${this.isOnline}`);
    });
  }

  getStatus() {
    return {
      online: this.isOnline,
      type: this.currentType
    };
  }

  destroy() {
    connection.off('netCapabilitiesChange');
    connection.off('netAvailable');
    connection.off('netLost');
  }
}

// 使用
const diag = new NetworkDiagnostics();
diag.init();

五、弱网检测与应对策略

// 检测弱网并降低资源消耗
class WeakNetworkHandler {
  private isWeakNetwork: boolean = false;
  private checkInterval: number = 3000; // 3秒检测一次

  async startMonitoring() {
    setInterval(async () => {
      try {
        const netHandle = await connection.getDefaultNet();
        const state = await connection.getNetCapabilities(netHandle);
        
        // 如果没有 INTERNET 能力或只有蜂窝(通常比WiFi慢),认为是弱网
        const hasInternet = state.networkCapabilities.includes(
          connection.NetCap.NET_CAPABILITY_INTERNET
        );
        const isCellularOnly = 
          state.bearerTypes.includes(connection.BearerType.CELLULAR) &&
          !state.bearerTypes.includes(connection.BearerType.WIFI);
        
        this.isWeakNetwork = !hasInternet || isCellularOnly;
        
        if (this.isWeakNetwork) {
          console.log('弱网环境,切换为低资源模式');
          // 降低图片质量
          // 减少预加载
          // 增加超时时间
        }
      } catch {
        this.isWeakNetwork = true;
      }
    }, this.checkInterval);
  }

  shouldLoadHDContent(): boolean {
    return !this.isWeakNetwork;
  }
}

六、API 速查表

API说明异步
getDefaultNet()获取默认网络
getNetCapabilities(handle)获取网络能力
getAddressesByName(handle, host)DNS解析
getDefaultHttpProxy()获取代理
on('netAvailable')网络可用监听-
on('netLost')网络丢失监听-
on('netCapabilitiesChange')网络能力变化-
on('netStateChange')网络状态变化-
off(event)移除监听-
BearerType说明
WIFIWiFi网络
CELLULAR蜂窝网络
ETHERNET以太网
BLUETOOTH蓝牙
NetCap说明
NET_CAPABILITY_INTERNET可访问互联网
NET_CAPABILITY_NOT_METERED非计费网络(如WiFi)
NET_CAPABILITY_NOT_VPN非VPN连接

总结

WiFi

蜂窝

无网络

connection.on监听网络变化

网络类型?

加载高清内容

降低流量消耗

显示离线状态/缓存数据

netCapabilitiesChange
实时更新

网络连接诊断是App体验的隐形护城河——好的App会在网络变化时无声地处理好一切,用户甚至不会察觉到。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐