如何判断当前手机网络是否可用?(HarmonyOS 鸿蒙Next)

如何判断当前手机网络是否可用?(HarmonyOS 鸿蒙Next)

请问能否使用下面代码,通过判断netId >0来判断当前网络是否可用?还是只能通过监听NetConnection的方式来使用一个静态变量来监听网络是否可用?

connection.getDefaultNet().then((data) => { 
  console.log(JSON.stringify(data));
})
5 回复

您可以参考下“网络连接管理”这个文档,通过接收状态变化通知来判断是否有网络,或者直接查询网络信息。

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/net-connection-manager-0000001820880297

更多关于如何判断当前手机网络是否可用?(HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-network-61-V5

function judgeHasNet(): boolean {
  try { // 获取当前网络连接
    let netHandle = connection.getDefaultNetSync();

    // 0-100 为系统预留的连接
    if (!netHandle || netHandle.netId < 100) {
      return false;
    }

    // 获取连接的属性
    let netCapability = connection.getNetCapabilitiesSync(netHandle);
    let cap = netCapability.networkCap;
    if (!cap) {
      return false;
    }

    for (let em of cap) {
      if (connection.NetCap.NET_CAPABILITY_VALIDATED === em) {
        return true;
      }
    }
  } catch (e) {
    let err = e as BusinessError;
    console.info('get netInfo error :' + JSON.stringify(err));
  }
  return false;
}

文档好像有说明,你可以看下

getDefaultNetSync 同步获取下?

在HarmonyOS(鸿蒙Next)中,判断当前手机网络是否可用可以通过@ohos.net.connection模块来实现。首先,使用getDefaultNet方法获取默认的网络连接对象,然后通过hasDefaultNet方法检查是否有默认网络连接。如果有默认网络连接,再使用getNetCapabilities方法获取网络能力,检查网络是否可用。

示例代码如下:

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

// 获取默认网络连接
let netConnection = connection.getDefaultNet();

// 检查是否有默认网络连接
if (netConnection.hasDefaultNet()) {
    // 获取网络能力
    let netCapabilities = netConnection.getNetCapabilities();
    
    // 检查网络是否可用
    if (netCapabilities.hasCapability(connection.NetCap.NET_CAPABILITY_INTERNET)) {
        console.log("网络可用");
    } else {
        console.log("网络不可用");
    }
} else {
    console.log("无网络连接");
}

这段代码通过检查默认网络连接及其能力来判断当前手机网络是否可用。如果有默认网络连接并且具备互联网能力,则判断网络可用,否则判断网络不可用。

回到顶部