需求场景:有部分应用在异常退出时希望重新被启动,无需用户手动操作。

需求分析:

我们还是可以使用在某个常驻服务来实现拉起操作,还是走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即可。

Logo

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

更多推荐