如何通过Service Ability实现设备状态的长时监控与断网自动重连?

如何通过Service Ability实现设备状态的长时监控与断网自动重连?

HarmonyOS Next
4天前
浏览
收藏 0
回答 2
已解决
回答 2
按赞同
/
按时间
金刚鹦鹉

一、ServiceAbility 的 ArkTS 实现1. 创建 ServiceAbility

使用 ​​ServiceExtensionAbility​​ 作为后台服务基类:


import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';

export default class MyServiceAbility extends ServiceExtensionAbility {
  onConnect(want: Want): void {
    console.log('ServiceAbility onConnect');
    // 初始化监控任务
    this.startMonitoring();
  }

  onDisconnect(want: Want): void {
    console.log('ServiceAbility onDisconnect');
    this.stopMonitoring();
  }

  // 启动设备监控逻辑
  private startMonitoring(): void {
    this.setupNetworkListener();
  }

  // 停止监控并释放资源
  private stopMonitoring(): void {
    this.removeNetworkListener();
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

2. 注册 ServiceAbility

在 ​​module.json5​​ 中声明后台服务:


{
  "module": {
    "abilities": [
      {
        "name": "MyServiceAbility",
        "type": "service",
        "backgroundModes": ["dataTransfer", "location"], // 后台模式
        "visible": true
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.GET_NETWORK_INFO",
        "reason": "Monitor network status"
      },
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING",
        "reason": "Keep service alive in background"
      }
    ]
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

二、网络状态监控与事件监听1. 使用 ​​@ohos.net.connection​​ 监听网络变化


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

class NetworkMonitor {
  private listenerId: number | null = null;

  // 注册网络状态监听
  registerNetworkListener(callback: (state: connection.NetState) => void): void {
    this.listenerId = connection.on('netAvailable', (data: { netHandle: connection.NetHandle }) => {
      const netState = connection.getDefaultNetSync();
      callback(netState);
    });
  }

  // 移除监听
  unregisterNetworkListener(): void {
    if (this.listenerId !== null) {
      connection.off('netAvailable', this.listenerId);
      this.listenerId = null;
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

2. 在 ServiceAbility 中集成网络监控


private networkMonitor: NetworkMonitor | null = null;

private setupNetworkListener(): void {
  this.networkMonitor = new NetworkMonitor();
  this.networkMonitor.registerNetworkListener((netState: connection.NetState) => {
    if (!netState.isAvailable) {
      this.handleNetworkDisconnected();
    } else {
      this.handleNetworkReconnected();
    }
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

三、断网自动重连策略1. 指数退避重连实现


private retryCount: number = 0;
private readonly MAX_RETRY: number = 5;

private async reconnect(): Promise<void> {
  while (this.retryCount < this.MAX_RETRY) {
    try {
      const success = await this.attemptReconnect();
      if (success) {
        this.retryCount = 0;
        return;
      }
    } catch (error) {
      console.error(`Reconnect attempt ${this.retryCount} failed: ${error}`);
    }

    // 指数退避延迟
    const delay = Math.pow(2, this.retryCount) * 1000;
    await new Promise(resolve => setTimeout(resolve, delay));
    this.retryCount++;
  }
}

private async attemptReconnect(): Promise<boolean> {
  const netState = connection.getDefaultNetSync();
  if (!netState.isAvailable) {
    return false;
  }
  // 具体重连逻辑(如重连服务器)
  return true;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

2. 使用 TaskPool 异步调度


import taskpool from '@ohos.taskpool';

private handleNetworkDisconnected(): void {
  taskpool.execute(async () => {
    await this.reconnect();
  }).catch((err) => {
    console.error(`Reconnect task failed: ${err}`);
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

四、后台保活与资源管理1. 申请持续后台运行权限


import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';

// 在 Service 启动时申请保活
private requestBackgroundMode(): void {
  backgroundTaskManager.requestSuspendDelay('NetworkMonitor', (err, delayId) => {
    if (err) {
      console.error(`Request background delay failed: ${err}`);
      return;
    }
    console.log(`Background delay granted, ID: ${delayId}`);
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

2. 释放资源

private removeNetworkListener(): void {
  if (this.networkMonitor) {
    this.networkMonitor.unregisterNetworkListener();
    this.networkMonitor = null;
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

五、调试与优化1. 日志记录


import hilog from '@ohos.hilog';

hilog.info(0x0000, 'NETWORK_TAG', 'Network state changed: %{public}s', state);
  • 1.
  • 2.
  • 3.

2. 性能优化

  • 减少高频操作:使用防抖(debounce)处理网络状态回调
  • 内存管理:避免闭包内存泄漏,及时释放无用对象

完整调用示例启动 ServiceAbility

import featureAbility from '@ohos.ability.featureAbility';

let want = {
  bundleName: 'com.example.myapp',
  abilityName: 'MyServiceAbility'
};
featureAbility.startAbility(want).then(() => {
  console.log('Service started');
}).catch((err) => {
  console.error(`Start service failed: ${err}`);
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

通过上述 ArkTS 代码,可实现基于 ServiceAbility 的持久化设备监控与智能重连机制。注意以下关键点:

  1. 网络状态依赖 @ohos.net.connection 模块
  2. 异步操作推荐使用 taskpool  Promise
  3. 后台保活需显式申请权限
分享
微博
QQ
微信
回复
1天前
梅科尔唐荣鑫


  1. 创建 Service Ability:在项目里创建一个 Service Ability,用来在后台持续运行监控任务。
  2. 设备状态监控:运用系统提供的 API 对设备的网络状态、电量等状态进行监控。
  3. 断网自动重连:当检测到网络断开时,尝试自动重新连接网络。
  4. Service 生命周期管理:对 Service 的生命周期进行管理,确保其在后台稳定运行。
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS websocket如何
819浏览 • 1回复 待解决
hi3861,mqtt断开自动问题
9441浏览 • 1回复 待解决
msyql 表查询怎么去
3323浏览 • 1回复 待解决
HarmonyOS 申请service Ability
466浏览 • 1回复 待解决
本地service本地应用间如何传递消息
6173浏览 • 1回复 待解决