| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- import { formBindingData, FormExtensionAbility, formProvider } from '@kit.FormKit';
- import { Want } from '@kit.AbilityKit';
- import { hilog } from '@kit.PerformanceAnalysisKit';
- import { WidgetData, WidgetSize } from '../common/widget/WidgetTypes';
- import { PreferencesUtil } from '../common/utils/PreferencesUtil';
- import { UnifiedPlayerService } from '../common/service/UnifiedPlayerService';
- import { VideoItem } from '../viewmodel/VideoItem';
- const TAG = 'Heanup EntryFormAbility';
- /**
- * 桌面播放器卡片扩展能力
- * 负责处理卡片的生命周期管理和用户交互事件
- * 支持多尺寸适配和UI重构
- */
- export default class EntryFormAbility extends FormExtensionAbility {
- private unifiedPlayerService:UnifiedPlayerService = UnifiedPlayerService.getInstance();
- // url -> fileName映射
- /**
- * 卡片创建时调用
- */
- onAddForm(want: Want): formBindingData.FormBindingData {
- // 检查参数有效性
- if (!want || !want.parameters) {
- hilog.error(0x0000, TAG, 'FormAbility onAddForm want or want.parameters is undefined');
- return formBindingData.createFormBindingData('');
- }
- // 初始化服务
- try {
- this.initializeServices();
- } catch (error) {
- hilog.error(0x0000, TAG, `Heanup EntryFormAbility failed to initialize services: ${error}`);
- }
- const formId = want.parameters?.['ohos.extra.param.key.form_identity'] as string;
- // 持久化保存 Form ID(异步执行,不阻塞返回)
- this.saveFormIdToPersistence(formId).then(() => {
- console.info('[Heanup] saveFormIdToPersistence success:'+ formId);
- })
- // 初始化卡片数据
- this.initializeWidget(formId);
- // 返回初始数据作为临时显示
- const adaptedData = this.buildWidgetData();
- return formBindingData.createFormBindingData(adaptedData);
- }
- /**
- * 卡片更新时调用
- */
- onUpdateForm(formId: string): void {
- // 只更新指定的卡片,避免重复更新
- this.updateWidgetData(formId);
- }
- /**
- * 卡片删除时调用
- */
- onRemoveForm(formId: string): void {
- // 从持久化存储中移除 Form ID(异步执行)
- this.removeFormIdFromPersistence(formId).then(() => {
- });
- }
- /**
- * 卡片可见性变化时调用
- */
- onVisibilityChange(newStatus: Record<string, number>): void {
- const formIds = Object.keys(newStatus);
- for (let i = 0; i < formIds.length; i++) {
- const formId = formIds[i];
- const isVisible = newStatus[formId] === 1;
- if (isVisible) {
- // 卡片变为可见时,更新数据
- this.updateWidgetData(formId);
- }
- }
- }
- /**
- * 卡片配置更新时调用
- */
- onConfigurationUpdate(newConfig: Object): void {
- // 更新所有卡片以适应新配置
- this.unifiedPlayerService.updateAllForms();
- }
- /**
- * 实现SizeChangeListener接口
- * 处理卡片尺寸变化事件
- */
- onSizeChanged(formId: string, oldSize: WidgetSize, newSize: WidgetSize): void {
- }
- /**
- * 处理卡片尺寸变化(系统调用)
- * @param newStatus 新的尺寸状态
- */
- onAcquireFormState(want: Want): number {
- // 返回卡片状态 - 使用数字常量代替枚举
- return 1; // READY状态
- }
- /**
- * 初始化服务
- */
- private initializeServices(): void {
- if (!this.unifiedPlayerService) {
- this.unifiedPlayerService = UnifiedPlayerService.getInstance();
- }
- }
- /**
- * 直接更新卡片(无网络图片)
- */
- private updateWidgetDirectly(formId: string, adaptedData: VideoItem, retryCount: number = 0): void {
- const formData = formBindingData.createFormBindingData(adaptedData);
- formProvider.updateForm(formId, formData).then(() => {
- }).catch(() => {
- hilog.error(0x0000, TAG, `Heanup widget ${formId} update failed, retry count: ${retryCount}`);
- // 重试机制:最多重试2次
- if (retryCount < 2) {
- setTimeout(() => {
- this.updateWidgetDirectly(formId, adaptedData, retryCount + 1);
- }, 1000 * (retryCount + 1)); // 递增延迟
- }
- });
- }
- /**
- * 获取默认卡片数据
- */
- private getDefaultWidgetData(): WidgetData {
- return {
- playState: {
- isPlaying: false,
- isPaused: true,
- isLoading: false
- },
- currentSong: {
- id: '',
- title: '暂无播放',
- artist: '未知艺术家',
- album: '未知专辑',
- coverImagePath: '',
- duration: 0
- },
- progress: {
- currentPosition: 0,
- duration: 0,
- percentage: 0,
- currentTimeText: '00:00',
- totalTimeText: '00:00'
- },
- playlist: {
- hasNext: false,
- hasPrevious: false,
- currentIndex: 0,
- totalCount: 0
- },
- config: {
- size: 'medium' as WidgetSize,
- theme: 'auto' as string,
- showProgress: true,
- showCover: true
- }
- };
- }
- /**
- * 初始化卡片
- */
- private async initializeWidget(formId: string): Promise<void> {
- try {
- // 立即更新一次卡片数据
- await this.updateWidgetData(formId);
- } catch (error) {
- hilog.error(0x0000, TAG, `Failed to initialize widget ${formId}: ${error}`);
- }
- }
- /**
- * 更新卡片数据(简化版本)
- */
- private async updateWidgetData(formId: string): Promise<void> {
- try {
- // 适配数据到当前尺寸并直接更新
- const adaptedData = this.buildWidgetData();
- const formData = formBindingData.createFormBindingData(adaptedData);
- await formProvider.updateForm(formId, formData);
- } catch (error) {
- hilog.error(0x0000, TAG, `Failed to update widget ${formId}: ${error}`);
- }
- }
- private buildWidgetData():VideoItem{
- let currentSong=this.unifiedPlayerService.getCurrentSong() as VideoItem;
- return currentSong;
- }
- /**
- * 保存 Form ID 到持久化存储
- */
- private async saveFormIdToPersistence(formId: string): Promise<void> {
- try {
- const preferencesUtil = PreferencesUtil.getInstance();
- const prefs = await preferencesUtil.getPreferences(this.context);
- await preferencesUtil.addFormId(prefs, formId);
- } catch (error) {
- hilog.error(0x0000, TAG, `❌ Failed to save Form ID: ${error}`);
- }
- }
- /**
- * 从持久化存储中移除 Form ID
- */
- private async removeFormIdFromPersistence(formId: string): Promise<void> {
- try {
- const preferencesUtil = PreferencesUtil.getInstance();
- const prefs = await preferencesUtil.getPreferences(this.context);
- await preferencesUtil.removeFormId(prefs, formId);
- } catch (error) {
- hilog.error(0x0000, TAG, `❌ Failed to remove Form ID: ${error}`);
- }
- }
- }
|