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

长时任务后台运行

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

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

使用的核心API

@ohos.app.ability.common';  
@ohos.app.ability.wantAgent';  
@ohos.resourceschedule.backgroundTaskManager';  
@ohos.hilog';  
@ohos.base';
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

核心代码解释

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") 
    } 
    ; 
  } 
}
  • 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.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.

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}) 
    } 
  } 
}
  • 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.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.

实现效果

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

分享
微博
QQ
微信
回复
2024-05-21 17:11:13
相关问题
HarmonyOS 如何保证应用后台不被挂起
1161浏览 • 1回复 待解决
如何申请多个时任务
2847浏览 • 1回复 待解决
HarmonyOS 时任务启动失败9800005
838浏览 • 1回复 待解决
HarmonyOS 申请时任务报错9800006 -
665浏览 • 1回复 待解决
时任务是否阻止系统休眠
866浏览 • 1回复 待解决
后台时任务启动失败
3014浏览 • 1回复 待解决
HarmonyOS 音视频时任务使用
989浏览 • 1回复 待解决
音视频播放是否需要创建时任务
2793浏览 • 1回复 待解决