像一些聊天软件,需要使用UDP进行数据传输,同时,需要保持后台长时运行,接收数据。但通常应用进入后台后,应用的进程会被挂起,导致无法接受数据,此时可以通过开启长时任务,保持应用在后台长时间运行,实现功能的正常使用。

开发步骤

1.配置长时任务类型

在模块级配置文件module.json5中配置数据传输长时任务

 "module": {
     "abilities": [
         {
             "backgroundModes": [
              // 长时任务类型的配置项
             "dataTransfer"
             ], 
             "skills": [
                 // 需添加隐式跳转的uris配置
                 {
                     "entities": [
                        "entity.system.home"
                     ],
                     "actions": [
                         "action.system.home"
                     ]    
                 },
                 {
                     "uris": [
                         {
                             "scheme": "test"
                         }
                     ]
                 }
             ]
         }
     ],
     ...
 }

2.开启和关闭长时任务

开启长时任务

startContinuousTask(): void {
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          //本应用包名和任务的ability名称
          bundleName: 'com.oh.dataTransferDemo',
          abilityName: 'com.oh.dataTransferDemo.MainAbility',
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    }

    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
      backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
        Logger.info(TAG, 'startBackgroundRunning succeeded');
        console.log('startBackgroundRunning succeeded');

      }).catch((error: BusinessError) => {
        console.log(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
        Logger.error(TAG, `Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
      });
    });
  }

关闭长时任务

stopContinuousTask(): void {
    try {
      backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
        Logger.info(TAG, `stopBackgroundRunning succeeded`);
        console.log(`stopBackgroundRunning succeeded`);
      }).catch((err: BusinessError) => {
        console.log(`stopBackgroundRunning failed Cause:  ${JSON.stringify(err)}`);
        Logger.info(TAG, `stopBackgroundRunning failed Cause:  ${JSON.stringify(err)}`);
      })
    } catch (error) {
      Logger.error(TAG, `stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
    }
  }

3.开启长时任务,绑定并开始监听消息

bindOption() {
    //绑定,开始监听消息
    let promise = udp.bind(this.localAddr);
    promise.then(() => {
      Logger.info(TAG, 'udp bind success');
    }).catch((err: BusinessError) => {
      Logger.info(TAG, `udp bind fail ${err}`);
    })
    udp.on('message', data => {
      const decoder = util.TextDecoder.create('utf-8');
      this.message = decoder.decodeWithStream(new Uint8Array(data.message));

      console.log(data.message.byteLength.toString());
    })
  }

//开启长时任务后,绑定本机地址,监听消息
let continuousTaskModel = new ContinuousTaskModel(this.context)
        continuousTaskModel.startContinuousTask();
        this.bindOption();

4.远端发送消息

let messageData='Hi'
          let sendOptions: socket.UDPSendOptions = {
            data: messageData,
            address: {
              //目标地址
              address: '172.20.10.2',
              port: 8080
            }
          }
          udp.send(sendOptions).then(() => {
            this.sendData=messageData;
            console.log('send success');
          }).catch((err: BusinessError) => {
            this.sendData=err.message
            console.log(`send fail, ${JSON.stringify(err)}`);
          });

开发参考文档:
1.长时任务
2.UDP通信

相关文件下载
DataTransfer.zip
701.46 KB
下载
Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐