鸿蒙系统开发【网络管理】

发布于:2024-08-02 ⋅ 阅读:(38) ⋅ 点赞:(0)

网络管理

介绍

此Demo展示如何查询网络详情、域名解析、网络状态监听等功能。

效果预览:

1

使用说明:

1.启动应用,在点击检查网络网络详情网络连接信息后,展示对应的信息;

2.在域名解析的模块下,输入对应的域名后,点击域名解析,展示解析的域名ip地址;

3.在网络监听模块下,开启网络监听后,展示当前监听的网络信息;关闭网络监听后,停止监听网络信息。

具体实现

使用@ohos.net.connection(网络连接管理)接口实现网络的详情、域名解析、网络监听等功能。代码:Index.ets

/*
 *
 *  * Copyright (c) 2023 Huawei Device Co., Ltd.
 *  * Licensed under the Apache License, Version 2.0 (the 'License');
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *     http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an 'AS IS' BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { CommonConstant as Const } from '../common/Constant';
import { promptAction } from '@kit.ArkUI';
import { Logger } from '../utils/Logger';

@Entry
@Component
struct Index {
  @State networkId: string = Const.NETWORK_ID;
  @State netMessage: string = Const.INIT_NET_MESSAGE;
  @State connectionMessage: string = Const.INIT_CONNECTION_MESSAGE;
  @State netStateMessage: string = '';
  @State hostName: string = '';
  @State ip: string = '';
  private controller: TabsController = new TabsController();
  private netHandle: connection.NetHandle | null = null;
  private netCon: connection.NetConnection | null = null;
  scroller: Scroller = new Scroller();

  aboutToDisappear(): void {
    this.unUseNetworkRegister;
  }

  build() {
    Column() {
      Text($r('app.string.network_title'))
        .fontSize($r('app.float.title_font_size'))
        .fontWeight(FontWeight.Bold)
        .textAlign(TextAlign.Start)
        .margin({ left: Const.WebConstant_TEN_PERCENT })
        .width(Const.WebConstant_FULL_WIDTH)

      Tabs({ controller: this.controller }) {
        TabContent() {
          Column() {
            Scroll() {
              Column() {
                Row() {
                  Column() {
                    Text($r('app.string.check_network'))
                      .fontSize($r('app.float.font_size'))
                      .padding({ top: $r('app.float.md_padding_margin'), left: $r('app.float.md_padding_margin') })
                      .fontWeight(FontWeight.Bold)
                      .align(Alignment.Start)
                      .width(Const.WebConstant_FULL_WIDTH)
                    Text(this.networkId)
                      .fontSize($r('app.float.font_size'))
                      .padding($r('app.float.md_padding_margin'))
                      .align(Alignment.Start)
                      .opacity($r('app.float.opacity'))
                      .width(Const.WebConstant_FULL_WIDTH)
                  }
                  .width(Const.WebConstant_SEVENTY_PERCENT)

                  Column() {
                    Button($r('app.string.check'))
                      .fontSize($r('app.float.sm_font_size'))
                      .height(Const.WebConstant_BUTTON_HEIGHT)
                      .margin({ top: $r('app.float.md_padding_margin') })
                      .width(Const.WebConstant_BUTTON_SMALL_WIDTH)
                      .buttonStyle(ButtonStyleMode.NORMAL)
                      .onClick(() => {
                        this.isNetworkAccess();
                      })
                  }
                  .align(Alignment.TopStart)
                  .height(Const.WebConstant_FULL_HEIGHT)
                  .width(Const.WebConstant_THIRTY_PERCENT)
                }
                .borderRadius($r('app.float.md_border_radius'))
                .margin({ left: $r('app.float.md_padding_margin'), right: $r('app.float.md_padding_margin') })
                .width(Const.WebConstant_NINETY_PERCENT)
                .height(Const.WebConstant_TWELVE_PERCENT)
                .backgroundColor($r('app.color.text_background'))

                Row() {
                  Column() {
                    Text($r('app.string.network_detail'))
                      .fontSize($r('app.float.font_size'))
                      .padding({ top: $r('app.float.md_padding_margin'), left: $r('app.float.md_padding_margin') })
                      .fontWeight(FontWeight.Bold)
                      .height(Const.WebConstant_FORTY_PERCENT)
                      .width(Const.WebConstant_FULL_WIDTH)
                    Text(this.netMessage)
                      .fontSize($r('app.float.font_size'))
                      .padding($r('app.float.md_padding_margin'))
                      .opacity($r('app.float.opacity'))
                      .height(Const.WebConstant_SIXTY_PERCENT)
                      .width(Const.WebConstant_FULL_WIDTH)
                  }
                  .width(Const.WebConstant_SEVENTY_PERCENT)
                  .align(Alignment.TopStart)

                  Column() {
                    Button($r('app.string.detail'))
                      .fontSize($r('app.float.sm_font_size'))
                      .height(Const.WebConstant_BUTTON_HEIGHT)
                      .margin({ top: $r('app.float.md_padding_margin') })
                      .width(Const.WebConstant_BUTTON_SMALL_WIDTH)
                      .buttonStyle(ButtonStyleMode.NORMAL)
                      .onClick(() => {
                        this.getNetworkMessage();
                      })
                  }
                  .align(Alignment.TopStart)
                  .height(Const.WebConstant_FULL_HEIGHT)
                  .width(Const.WebConstant_THIRTY_PERCENT)
                }
                .borderRadius($r('app.float.md_border_radius'))
                .margin($r('app.float.md_padding_margin'))
                .width(Const.WebConstant_NINETY_PERCENT)
                .height(Const.WebConstant_FIFTEEN_PERCENT)
                .backgroundColor($r('app.color.text_background'))

                Row() {
                  Column() {
                    Text($r('app.string.network_connection_detail'))
                      .fontSize($r('app.float.font_size'))
                      .padding($r('app.float.md_padding_margin'))
                      .fontWeight(FontWeight.Bold)
                      .width(Const.WebConstant_FULL_WIDTH)
                      .align(Alignment.Start)
                    Text(this.connectionMessage)
                      .fontSize($r('app.float.font_size'))
                      .opacity($r('app.float.opacity'))
                      .width(Const.WebConstant_NINETY_PERCENT)
                      .align(Alignment.Start)
                  }
                  .width(Const.WebConstant_SEVENTY_PERCENT)
                  .justifyContent(FlexAlign.Start)

                  Column() {
                    Button($r('app.string.detail'))
                      .fontSize($r('app.float.sm_font_size'))
                      .height(Const.WebConstant_BUTTON_HEIGHT)
                      .margin({ top: $r('app.float.md_padding_margin') })
                      .width(Const.WebConstant_BUTTON_SMALL_WIDTH)
                      .buttonStyle(ButtonStyleMode.NORMAL)
                      .onClick(() => {
                        this.getConnectionProperties();
                      })
                  }
                  .width(Const.WebConstant_THIRTY_PERCENT)
                }
                .alignItems(VerticalAlign.Top)
                .borderRadius($r('app.float.md_border_radius'))
                .margin({
                  left: $r('app.float.md_padding_margin'),
                  right: $r('app.float.md_padding_margin'),
                  bottom: $r('app.float.xl_padding_margin')
                })
                .width(Const.WebConstant_NINETY_PERCENT)
                .backgroundColor($r('app.color.text_background'))

              }
              .alignItems(HorizontalAlign.Start)
            }
          }
          .height(Const.WebConstant_FULL_HEIGHT)
          .alignItems(HorizontalAlign.Start)
        }.tabBar(Const.FIRST_TABS_BAR)

        TabContent() {
          Column() {
            Search({ placeholder: Const.SEARCH_PLACEHOLDER })
              .margin({ left: $r('app.float.md_padding_margin'), right: $r('app.float.md_padding_margin') })
              .width(Const.WebConstant_NINETY_PERCENT)
              .searchButton(Const.SEARCH_BUTTON)
              .onSubmit((value: string) => {
                this.hostName = value;
                this.parseHostName(this.hostName);
              })

            TextArea({ text: this.ip })
              .fontSize($r('app.float.lg_font_size'))
              .width(Const.WebConstant_NINETY_PERCENT)
              .height(Const.WebConstant_FIFTY_PERCENT)
              .margin({ top: $r('app.float.md_padding_margin') })
              .borderRadius($r('app.float.md_border_radius'))
              .focusOnTouch(false)
          }
          .height(Const.WebConstant_FULL_HEIGHT)
          .justifyContent(FlexAlign.Start)

        }.tabBar(Const.SECOND_TABS_BAR)

        TabContent() {
          Column() {
            Row() {
              Text(Const.MONITOR_TITLE)
                .fontSize($r('app.float.font_size'))
                .margin($r('app.float.md_padding_margin'))
                .fontWeight(FontWeight.Medium)
              Blank()
              Toggle({ type: ToggleType.Switch, isOn: false })
                .selectedColor(Color.Blue)
                .margin({ right: $r('app.float.md_padding_margin') })
                .width($r('app.float.area_width'))
                .height(Const.WebConstant_BUTTON_HEIGHT)
                .onChange((isOn) => {
                  if (isOn) {
                    this.useNetworkRegister();
                  } else {
                    this.unUseNetworkRegister();
                  }
                })
            }
            .height($r('app.float.button_height'))
            .borderRadius($r('app.float.md_border_radius'))
            .margin({ left: $r('app.float.md_padding_margin'), right: $r('app.float.md_padding_margin') })
            .width(Const.WebConstant_NINETY_PERCENT)
            .backgroundColor($r('app.color.text_background'))

            TextArea({ text: this.netStateMessage })
              .fontSize($r('app.float.font_size'))
              .width(Const.WebConstant_NINETY_PERCENT)
              .height(Const.WebConstant_FIVE_HUNDRED)
              .margin($r('app.float.md_padding_margin'))
              .borderRadius($r('app.float.md_border_radius'))
              .textAlign(TextAlign.Start)
              .focusOnTouch(false)

            Button($r('app.string.clear'))
              .fontSize($r('app.float.font_size'))
              .width(Const.WebConstant_NINETY_PERCENT)
              .height($r('app.float.area_height'))
              .margin({
              left: $r('app.float.md_padding_margin'),
              right: $r('app.float.md_padding_margin'),
              bottom: $r('app.float.xxl_padding_margin')
            })
              .onClick(() => {
                this.netStateMessage = '';
              })
            Blank()
          }
          .height(Const.WebConstant_FULL_HEIGHT)
          .justifyContent(FlexAlign.Start)

        }.tabBar(Const.THIRD_TABS_BAR_THREE)
      }
      .barWidth(Const.WebConstant_EIGHTY_PERCENT)
    }
    .width(Const.WebConstant_FULL_WIDTH)
  }

  isNetworkAccess() {
    connection.hasDefaultNet((error: BusinessError) => {
      if (error) {
        this.networkId = Const.NETWORK_ERROR;
        Logger.error('hasDefaultNet error:' + error.message);
        return;
      }
      this.netHandle = connection.getDefaultNetSync();
      this.networkId = Const.NETWORK_ID + JSON.stringify(this.netHandle);
    })
  }

  getNetworkMessage() {
    if (this.netHandle) {
      connection.getNetCapabilities(this.netHandle, (error, netCap) => {
        if (error) {
          this.netMessage = Const.NETWORK_TYPE_ERROR;
          Logger.error('getNetCapabilities error:' + error.message);
          return;
        }
        let netType = netCap.bearerTypes;
        for (let i = 0; i < netType.length; i++) {
          if (netType[i] === 0) {
            this.netMessage = Const.CELLULAR_NETWORK;
          } else if (netType[i] === 1) {
            this.netMessage = Const.WIFI_NETWORK;
          } else {
            this.netMessage = Const.OTHER_NETWORK;
          }
        }
        this.netMessage += 'networkCap:' + JSON.stringify(netCap.networkCap) + '\n';
      })
    }
  }

  getConnectionProperties() {
    connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
      connection.getConnectionProperties(netHandle, (error: BusinessError, connectionProperties: connection.ConnectionProperties) => {
        if (error) {
          this.connectionMessage = Const.CONNECTION_PROPERTIES_ERROR;
          Logger.error('getConnectionProperties error:' + error.code + error.message);
          return;
        }
        this.connectionMessage = Const.CONNECTION_PROPERTIES_INTERFACE_NAME + connectionProperties.interfaceName
          + Const.CONNECTION_PROPERTIES_DOMAINS + connectionProperties.domains
          + Const.CONNECTION_PROPERTIES_LINK_ADDRESSES + JSON.stringify(connectionProperties.linkAddresses)
          + Const.CONNECTION_PROPERTIES_ROUTES + JSON.stringify(connectionProperties.routes)
          + Const.CONNECTION_PROPERTIES_LINK_ADDRESSES + JSON.stringify(connectionProperties.dnses)
          + Const.CONNECTION_PROPERTIES_MTU + connectionProperties.mtu + '\n';
      })
    });
  }

  parseHostName(hostName: string) {
    this.ip = '';
    connection.getAddressesByName(hostName).then((data) => {
      for (let i = 0; i < data.length; i++) {
        this.ip += data[i].address + '\n';
      }
    })
      .catch((error: BusinessError) => {
        this.ip = Const.GET_ADDRESSES_ERROR;
        Logger.error('getAddressesByName error:' + error.message);
      })
  }

  useNetworkRegister() {
    this.netCon = connection.createNetConnection();
    this.netStateMessage += Const.REGISTER_NETWORK_LISTENER;
    this.netCon.register((error) => {
      if (error) {
        Logger.error('register error:' + error.message);
        return;
      }
      promptAction.showToast({
        message: Const.REGISTER_NETWORK_LISTENER_MESSAGE,
        duration: 1000
      });
    })
    this.netCon.on('netAvailable', (netHandle) => {
      this.netStateMessage += Const.NET_AVAILABLE + netHandle.netId + '\n';
    })
    this.netCon.on('netBlockStatusChange', (data) => {
      this.netStateMessage += Const.NET_BLOCK_STATUS_CHANGE + data.netHandle.netId + '\n';
    })
    this.netCon.on('netCapabilitiesChange', (data) => {
      this.netStateMessage += Const.NET_CAPABILITIES_CHANGE_ID + data.netHandle.netId
        + Const.NET_CAPABILITIES_CHANGE_CAP + JSON.stringify(data.netCap) + '\n';
    })
    this.netCon.on('netConnectionPropertiesChange', (data) => {
      this.netStateMessage += Const.NET_CONNECTION_PROPERTIES_CHANGE_ID + data.netHandle.netId
        + Const.NET_CONNECTION_PROPERTIES_CHANGE_CONNECTION_PROPERTIES + JSON.stringify(data.connectionProperties) + '\n';
    })
  }

  unUseNetworkRegister() {
    if (this.netCon) {
      this.netCon.unregister((error: BusinessError) => {
        if (error) {
          Logger.error('unregister error:' + error.message);
          return;
        }
        promptAction.showToast({
          message: Const.UNREGISTER_NETWORK_LISTENER_MESSAGE,
          duration: 1000
        });
        this.netStateMessage += Const.UNREGISTER_NETWORK_LISTENER;
      })
    } else {
      this.netStateMessage += Const.UNREGISTER_NETWORK_LISTENER_FAIL;
    }
  }
}

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
1

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

在这里插入图片描述

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!