[经验分享] OpenHarmony 4.0 Release 循环拉起应用功能 原创

onefan 显示全部楼层 发表于 7 天前
需求场景:有部分应用在异常退出时希望重新被启动,无需用户手动操作。
需求分析:

我们还是可以使用在某个常驻服务来实现拉起操作,还是走launcher创建窗口时来实现。此时我们需要去监听某个应用被杀死的状态,刚好 appManager.on(‘applicationState’, applicationStateObserver)这个接口实现了监听应用的状态,并在onProcessDied中可以查询到指定应用的bundleName列表,依赖来实现再次拉起指定应用的场景。

代码示例:
            //新增需求,xxx应用被杀掉后需要再此被拉起
            let applicationStateObserver: appManager.ApplicationStateObserver = {
              onForegroundApplicationChanged(appStateData) {
                console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`);
              },
              onAbilityStateChanged(abilityStateData) {
                console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
              },
              onProcessCreated(processData) {
                console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`);
              },
              onProcessDied(processData) {
                console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`);
                if(processData.bundleName === 'com.xx.xxx'){
                  if (systemparameter.getSync('persist.autostart.xxx', '0') === '1') {
                    setTimeout(() => {
                      let want = {
                        "deviceId": "",
                        "bundleName": "com.xx.xxx",
                        "abilityName": "EntryAbility"
                      };
                      globalThis.desktopContext.startAbility(want).then(() => {
                        Log.showInfo(TAG, '[appManager] OneFan processData startAbility success');
                      }).catch((error) => {
                        Log.showInfo(TAG, '[appManager] OneFan processData startAbility failed');
                      })
                    }, 500)
                  } else {
                    Log.showInfo(TAG, '[appManager] OneFan processData persist.autostart.dts err');
                  }
                }
              },
              onProcessStateChanged(processData) {
                console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
              }
            };
            try {
              const observerId = appManager.on('applicationState', applicationStateObserver);
              console.log(`[appManager] observerCode: ${observerId}`);
            } catch (paramError) {
              let code = (paramError as BusinessError).code;
              let message = (paramError as BusinessError).message;
              console.error(`[appManager] error: ${code}, ${message} `);
            }
            //新增需求,xxx应用被杀掉后需要再此被拉起

而相对于服务型应用来说,我们只需要在install_list_capability.json及签名中配置keepAlive为true即可。

©著作权归作者所有,转载或内容合作请联系作者

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

精彩评论1

YuqiZ

来自手机 沙发 发表于 7 天前
学会了学会了谢谢🙏

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部