全局订阅网络状态变化，如何在具体页面控制业务
======================

#### 问题现象

如何在应用全局订阅网络状态，在不同子页面根据网络变化处理业务。

#### 背景知识

*   [接收指定网络的状态变化通知](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/net-connection-manager#接收指定网络的状态变化通知)。
*   应用全局的UI状态存储：[AppStorage](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-appstorage)、[@StorageProp](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-appstorage#storageprop)。
*   应用状态管理装饰器：[@Watch](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-watch)。

#### 解决方案

1.  在应用启动后，EntryAbility中注册监听网络状态变化，监听到网络状态后存储在AppStorage中。
    
    onWindowStageCreate(windowStage: window.WindowStage): void {
      _// Main window is created, set main page for this ability_
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    
      windowStage.loadContent('pages/Index', (err) => {
        if (err.code) {
          hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
          return;
        }
        this.netWork.register();
        hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
      });
    }
    
    注册监听网络状态变化的具体实现在NetWork工具类中。
    
    register(): void {
     _ // 订阅网络能力变化事件_
      this.netConnect.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
        let netAvailable = data.netCap.networkCap?.includes(connection.NetCap.NET\_CAPABILITY\_INTERNET);
        AppStorage.setOrCreate('netAvailable', netAvailable);
      });
    
     _ // 订阅网络丢失事件_
      this.netConnect.on('netLost', () => {
        AppStorage.setOrCreate('netAvailable', false);
      });
    
      _// 初始化注册_
      this.netConnect.register((error: BusinessError) => {
        if (error) {
          console.log('AppNetStatus', 'register net failed');
          return;
        }
        console.log('AppNetStatus', 'register net success');
      });
    }
    
2.  在具体的page页面中实时接收网络状态变化，控制业务。
    
    @Entry
    @Component
    struct Index {
      @StorageProp('netAvailable') @Watch('onNetStatusChange') netAvailable: boolean = true;
      @State message: string = '网络正常';
      @State color: ResourceColor = Color.Green;
    
      build() {
        Column() {
          Text(this.message)
            .fontSize(48)
            .fontColor(this.color)
        }
        .justifyContent(FlexAlign.Center)
        .width('100%')
        .height('100%')
      }
    
      onNetStatusChange() {
        if (this.netAvailable) { _// 网络恢复时重连业务_
          this.message = '网络正常';
          this.color = Color.Green;
        } else { _// 显示离线状态UI_
          this.message = '网络异常';
          this.color = Color.Red;
        }
      }
    }
    
3.  退出应用后在EntryAbility中注销监听网络状态变化。
    
    onWindowStageDestroy(): void {
      _// Main window is destroyed, release UI related resources_
      this.netWork.unregister();
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
    }
    
4.  需要添加权限。
    
    "requestPermissions": \[
      { "name": "ohos.permission.GET\_NETWORK\_INFO" }
    \],
    

完整示例参考如下：

import { ConfigurationConstant, UIAbility } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import NetWork from '../NetWork';

const DOMAIN = 0x0000;

export default class EntryAbility extends UIAbility {
  private netWork: NetWork = new NetWork();
  onCreate(): void {
    try {
      this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR\_MODE\_NOT\_SET);
    } catch (err) {
      hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
    }
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy(): void {
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
  _  // Main window is created, set main page for this ability_
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      this.netWork.register();
      hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    });
  }

  onWindowStageDestroy(): void {
   _ // Main window is destroyed, release UI related resources_
    this.netWork.unregister();
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
   _ // Ability has brought to foreground_
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
   _ // Ability has back to background_
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
  }
}

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

export default class NetWork {
  private netConnect: connection.NetConnection = connection.createNetConnection();

  register(): void {
   _ // 订阅网络能力变化事件_
    this.netConnect.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
      let netAvailable = data.netCap.networkCap?.includes(connection.NetCap.NET\_CAPABILITY\_INTERNET);
      AppStorage.setOrCreate('netAvailable', netAvailable);
    });

  _  // 订阅网络丢失事件_
    this.netConnect.on('netLost', () => {
      AppStorage.setOrCreate('netAvailable', false);
    });

  _  // 初始化注册_
    this.netConnect.register((error: BusinessError) => {
      if (error) {
        console.log('AppNetStatus', 'register net failed');
        return;
      }
      console.log('AppNetStatus', 'register net success');
    });
  }

  unregister(): void {
    if (this.netConnect) {
      this.netConnect.unregister((error: BusinessError) => {
        if (error) {
          console.log('register net failed');
          return;
        }
        console.log('register net success');
      });
    }
  }
}

@Entry
@Component
struct Index {
  @StorageProp('netAvailable') @Watch('onNetStatusChange') netAvailable: boolean = true;
  @State message: string = '网络正常';
  @State color: ResourceColor = Color.Green;

  build() {
    Column() {
      Text(this.message)
        .fontSize(48)
        .fontColor(this.color)
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }

  onNetStatusChange() {
    if (this.netAvailable) { _// 网络恢复时重连业务_
      this.message = '网络正常';
      this.color = Color.Green;
    } else { _// 显示离线状态UI_
      this.message = '网络异常';
      this.color = Color.Red;
    }
  }
}