420aa215创建于 24 天前历史提交
/*
 * Copyright (c) 2026 Huawei Device Co., Ltd.
 * Licensed under Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with License.
 * You may obtain a copy of License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { insightIntent, InsightIntentExecutor } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { AudioControlCenter } from '../common/utils/audioutils/AudioControlCenter';
import Logger from '../common/utils/Logger';

const TAG = 'InsightIntentExecutorImpl';

export default class InsightIntentExecutorImpl extends InsightIntentExecutor {
  // [Start onExecuteInUIAbilityBackgroundMode]
  private audioControlCenter: AudioControlCenter = AudioControlCenter.getInstance();

  async onExecuteInUIAbilityBackgroundMode(intentName: string, intentParam: Record<string, Object>):
    Promise<insightIntent.ExecuteResult> {
    Logger.info(TAG, `onExecuteInUIAbilityBackgroundMode, intentName: ${intentName}`);

    switch (intentName) {
      case 'PlayMusic':
        let data = intentParam as Record<string, string>;
        return this.playFunc(data.entityId);
      case 'PlayMusicList':
        let entityId: string = (intentParam.items as Array<object>)?.[0]?.['entityId'];
        return this.playFunc(entityId);
      default:
        break;
    }

    return Promise.resolve({
      code: -1,
      result: { message: 'unknown intent' }
    } as insightIntent.ExecuteResult)
  }
  // [End onExecuteInUIAbilityBackgroundMode]

  private playFunc(entityId: string): Promise<insightIntent.ExecuteResult> {
    Logger.info(TAG, `playFunc, entityId: ${entityId}`);
    return new Promise(async (resolve) => {
      try {
        if (entityId && entityId.length > 0) {
          Logger.info(TAG, `Play specific queue: ${entityId}`);
          await this.startPlayback(entityId);
        } else {
          Logger.info(TAG, 'Resume last played content');
          await this.startPlayback('');
        }

        resolve({
          code: 0,
          result: {
            message: 'Intent execute succeeded'
          }
        } as insightIntent.ExecuteResult);
      } catch (error) {
        Logger.error(TAG, `playFunc failed: ${JSON.stringify(error)}`);
        resolve({
          code: -1,
          result: {
            message: 'Intent execute failed'
          }
        } as insightIntent.ExecuteResult);
      }
    });
  }

  private async startPlayback(entityId: string): Promise<void> {
    await this.audioControlCenter.init();
    await this.audioControlCenter.play();
  }
}