HarmonyOS应用开发实战:猫猫大作战-背景任务的申请与 BG 模式

HarmonyOS应用开发实战:猫猫大作战-背景任务的申请与 BG 模式 前言backgroundTasksKit提供了后台任务能力允许应用在后台持续运行有限时长。在「猫猫大作战」中当游戏进行中用户切到后台时我们需要申请后台任务让游戏继续运行或者至少保存当前状态。一、后台任务申请import{backgroundTaskManager}fromkit.BackgroundTasksKit;asyncfunctionrequestBackgroundRunning(context:Context):Promisevoid{try{awaitbackgroundTaskManager.startBackgroundRunning(context,backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK);console.info(后台运行已申请);}catch(err){console.error(后台运行申请失败:${err.message});}}asyncfunctionstopBackgroundRunning(context:Context):Promisevoid{try{awaitbackgroundTaskManager.stopBackgroundRunning(context);console.info(后台运行已停止);}catch(err){console.error(停止后台运行失败:${err.message});}}二、支持的 BackgroundMode模式说明游戏中使用AUDIO_PLAYBACK音频播放背景音乐继续播放LOCATION定位地理位置排行DATA_TRANSFER数据传输战绩同步TASK短暂任务状态保存三、在游戏中的集成onBackground(){if(this.gameStateGameState.PLAYING){// 申请后台运行保存游戏状态requestBackgroundRunning(getContext()asContext);// 暂停游戏循环this.gameStateGameState.PAUSED;this.clearTimers();// 保存游戏快照AppStorage.setOrCreate(savedGame,{score:this.score,cats:this.cats,gameTime:this.gameTime,});}}onForeground(){stopBackgroundRunning(getContext()asContext);// 恢复游戏状态constsavedAppStorage.getSavedGame(savedGame);if(savedthis.gameStateGameState.PAUSED){this.scoresaved.score;this.catssaved.cats;this.gameTimesaved.gameTime;this.resumeGame();}}四、限制说明限制说明单次最长3 分钟普通任务/ 更长音频任务每日配额系统根据使用频率动态分配必须用户可见时申请切后台前后台任务电量影响长时间后台运行会显著增加耗电五、最佳实践仅必要时申请只在游戏进行中切后台时申请回前台立即停止在onForeground中调用stopBackgroundRunning状态保存后台任务首要目标是保存游戏状态音频模式保活带 BGM 时用AUDIO_PLAYBACK模式总结backgroundTasksKit 的后台任务能力让游戏在切后台时保存状态。核心要点startBackgroundRunning申请、BackgroundMode根据用途选择、 回前台立即停止、 优先保存游戏状态。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源backgroundTaskManager API后台任务开发指南第 160 篇Payment第 162 篇bg-running