长时任务后台运行,保证应用不被挂起

长时任务后台运行

HarmonyOS
2024-05-20 21:16:37
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
e_leaner

开启后台任务运行,保证应用不被挂起

使用的核心API

@ohos.app.ability.common';  
@ohos.app.ability.wantAgent';  
@ohos.resourceschedule.backgroundTaskManager';  
@ohos.hilog';  
@ohos.base';

核心代码解释

1 创建长时任务工具类

import common from '@ohos.app.ability.common'; 
import wantAgent from '@ohos.app.ability.wantAgent'; 
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 
import hilog from '@ohos.hilog'; 
import { BusinessError } from '@ohos.base'; 
 
const TAG = 'testTag'; 
 
export class BackgroundUtil { 
  /** 
   * Start background task. 
   * 
   * @param context 
   */ 
  public static startContinuousTask(context: common.UIAbilityContext): void { 
    hilog.info(0x00000, TAG, '启动长时任务'); 
    let wantAgentInfo: wantAgent.WantAgentInfo = { 
      wants: [ 
        { 
          bundleName: context.abilityInfo.bundleName, 
          abilityName: context.abilityInfo.name 
        } 
      ], 
      actionType: wantAgent.OperationType.START_ABILITY, 
      requestCode: 0, 
      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 
    }; 
 
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { 
      try { 
        backgroundTaskManager.startBackgroundRunning(context, backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj) 
          .then(() => { 
            hilog.info(0x0000, TAG, 'startBackgroundRunning succeeded'); 
          }) 
          .catch((err: BusinessError) => { 
            hilog.error(0x0000, TAG, `startBackgroundRunning failed Cause: ${JSON.stringify(err)}`); 
          }); 
      } catch (error) { 
        hilog.error(0x0000, TAG, `stopBackgroundRunning failed. error: ${JSON.stringify(error)} `); 
      } 
    }); 
  } 
 
  /** 
   * Stop background task. 
   * 
   * @param context 
   */ 
  public static stopContinuousTask(context: common.UIAbilityContext): void { 
    hilog.info(0x00000, TAG, '停止长时任务'); 
    try { 
      backgroundTaskManager.stopBackgroundRunning(context).then(() => { 
        hilog.info(0x0000, TAG, 'stopBackgroundRunning succeeded'); 
      }).catch((err: BusinessError) => { 
        hilog.error(0x0000, TAG, `stopBackgroundRunning failed Cause: ${JSON.stringify(err)}`); 
      }) 
    } catch (error) { 
      hilog.error(0x0000, TAG, "stopBackgroundRunning") 
    } 
    ; 
  } 
}

2 主页调用长时任务后台运行

import geoLocationManager from '@ohos.geoLocationManager'; 
import { PermissionUtils } from './PermissionUtils'; 
import common from '@ohos.app.ability.common'; 
import { BackgroundUtil } from './BackgroundUtil'; 
import hilog from '@ohos.hilog'; 
const TAG: string = 'testTag' 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
  @State count: number = 0; 
  @State handlePopup: boolean = false 
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 
 
  aboutToAppear() { 
    PermissionUtils.requestPermissionsFromUser(["ohos.permission.APPROXIMATELY_LOCATION", 'ohos.permission.LOCATION'], getContext(this) as common.UIAbilityContext); 
    // setInterval(() => { 
    //   this.count++; 
    // }, 1000); 
  } 
 
  onPageHide() { 
    setInterval(() => { 
      this.count++; 
    }, 1000); 
  } 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.count.toString()) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold); 
 
        Button("开启长时任务").onClick(() => { 
          console.log("123456") 
          let requestInfo: geoLocationManager.LocationRequest = { 
            'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 
            'timeInterval': 0, 
            'distanceInterval': 0, 
            'maxAccuracy': 0 
          }; 
          let locationChange = (location: geoLocationManager.Location): void => { 
            console.log('locationChanger: data: ' + JSON.stringify(location)); 
          }; 
          geoLocationManager.on('locationChange', requestInfo, locationChange); 
          BackgroundUtil.startContinuousTask(this.context); 
          this.handlePopup = true; 
        }).bindPopup(this.handlePopup, { 
          message: '开启长时任务成功', 
        }).margin({ 
          bottom: '5%' 
        }) 
          .align(Alignment.Center) 
 
        Button("关闭长时任务").onClick(() => { 
          BackgroundUtil.stopContinuousTask(this.context); 
        }) 
          .bindPopup(!this.handlePopup, { 
          message: '关闭长时状态', 
        }).margin({ 
         /* bottom: '1%'*/ 
        }).backgroundColor(Color.Red) 
          .width('50%') 
      }     .alignItems(HorizontalAlign.Center) 
      .justifyContent(FlexAlign.SpaceAround) 
      .size({width: "100%", height: 120}) 
    } 
  } 
}

实现效果

开启后台任务运行,保证应用不被挂起,在后台进行位置信息定位。

分享
微博
QQ
微信
回复
2024-05-21 17:11:13
相关问题
如何申请多个时任务
774浏览 • 1回复 待解决
后台时任务启动失败
795浏览 • 1回复 待解决
音视频播放是否需要创建时任务
716浏览 • 1回复 待解决
后台时任务启动失败报错码201
796浏览 • 1回复 待解决
如何让应用后台持续运行
15592浏览 • 2回复 待解决
音频播放长时任务不生效
598浏览 • 1回复 待解决
请问用什么接口可以实现定时任务
536浏览 • 0回复 待解决
如何实现定时任务有懂的吗?
1349浏览 • 1回复 待解决
如何设置组件定时任务和定时器
51浏览 • 1回复 待解决
智能穿戴如何启用后台任务?
1376浏览 • 1回复 待解决