1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import connection from '@ohos.net.connection';
17import { LogUtils } from '../util/LogUtils';
18
19/**
20 * 网络判断工具类
21 *
22 * @since 2022-08-25
23 */
24export namespace NetUtils {
25  /**
26   * 网络是否可用
27   *
28   * @return 网络是否可用
29   */
30  export async function isNetAvailable(): Promise<boolean> {
31    return new Promise((resolve, reject) => {
32      connection.getDefaultNet().then((netHandle) => {
33        LogUtils.log('NetUtils', 'getDefaultNet data ' + JSON.stringify(netHandle));
34        connection.getNetCapabilities(netHandle).then((info) => {
35          LogUtils.log('NetUtils', 'getNetCapabilities data ' + JSON.stringify(info));
36          resolve(info?.bearerTypes?.length !== 0);
37        }).catch((err) => {
38          LogUtils.log('NetUtils', 'getNetCapabilities err ' + JSON.stringify(err));
39          resolve(false);
40        });
41      }).catch((err) => {
42        LogUtils.log('NetUtils', 'getDefaultNet err ' + JSON.stringify(err));
43        resolve(false);
44      });
45    });
46  }
47
48  /**
49   * 是否是蜂窝网络
50   *
51   * @return 是否是蜂窝网络
52   */
53  export async function isCellularNetwork(): Promise<boolean> {
54    return new Promise((resolve, reject) => {
55      connection.getDefaultNet().then((netHandle) => {
56        LogUtils.log('NetUtils', 'getDefaultNet data ' + JSON.stringify(netHandle));
57        connection.getNetCapabilities(netHandle).then((info) => {
58          LogUtils.log('NetUtils', 'getNetCapabilities data ' + JSON.stringify(info));
59          resolve(info?.bearerTypes?.length === 1 && info?.bearerTypes?.[0] === connection.NetBearType.BEARER_CELLULAR);
60        }).catch((err) => {
61          LogUtils.log('NetUtils', 'getNetCapabilities err ' + JSON.stringify(err));
62          resolve(false);
63        });
64      }).catch((err) => {
65        LogUtils.log('NetUtils', 'getDefaultNet err ' + JSON.stringify(err));
66        resolve(false);
67      });
68    });
69  }
70}