/** * 应用主Ability入口文件 * 功能: * 1. 管理应用生命周期 * 2. 处理窗口创建和尺寸变化 * 3. 响应外部调用请求 * 4. 全局状态管理 */ import UIAbility from '@ohos.app.ability.UIAbility'; import hilog from '@ohos.hilog'; import window from '@ohos.window'; import { AbilityConstant, Want } from '@kit.AbilityKit'; import { BusinessError, emitter } from '@kit.BasicServicesKit'; import { AppUtil, ArrayUtil, GlobalContext, LogUtil, StrUtil } from '@pura/harmony-utils'; import { rpc } from '@kit.IPCKit'; import { Utility } from '../common/util/Utility'; import { WXApi, WXEventHandler } from '../common/util/WXApiWrap'; import { UnifiedPlayerService } from '../common/service/UnifiedPlayerService'; import { WidgetRegistrationFix } from '../common/widget/WidgetRegistrationFix'; import { systemShare } from '@kit.ShareKit'; import { SpiderMan } from '@simplepeng/spider-man'; import { smartMobilityCommon } from '@kit.CarKit'; /** * RPC通信返回类型的实现,用于RPC通信数据序列化和反序列化 */ class MyParcelable implements rpc.Parcelable { num: number; str: string; constructor(num: number, str: string) { this.num = num; this.str = str; } marshalling(messageSequence: rpc.MessageSequence): boolean { messageSequence.writeInt(this.num); messageSequence.writeString(this.str); return true; } unmarshalling(messageSequence: rpc.MessageSequence): boolean { this.num = messageSequence.readInt(); this.str = messageSequence.readString(); return true; } } /** * 主Ability类,继承自UIAbility * 负责: * - 应用初始化 * - 窗口管理 * - 事件分发 */ export default class EntryAbility extends UIAbility { // UI上下文对象,用于获取窗口信息 private uiContext?: UIContext; private awareness: smartMobilityCommon.SmartMobilityAwareness = smartMobilityCommon.getSmartMobilityAwareness(); /** * 窗口尺寸变化回调函数 * @param windowSize 新的窗口尺寸对象 * 功能: * 1. 获取最新的窗口断点尺寸 * 2. 更新AppStorage中的尺寸状态 * 3. 记录尺寸变化日志 */ private onWindowSizeChange: (windowSize: window.Size) => void = async (windowSize: window.Size) => { // 获取宽度断点并更新全局状态 let widthBp = this.uiContext!.getWindowWidthBreakpoint(); AppStorage.setOrCreate('currentWidthBreakpoint', widthBp); // 获取高度断点并更新全局状态 let heightBp = this.uiContext!.getWindowHeightBreakpoint(); AppStorage.setOrCreate('currentHeightBreakpoint', heightBp); // 记录尺寸变化日志 // LogUtil.info('pura onWindowSizeChange currentHeightBreakpoint= '+heightBp); // LogUtil.info( 'pura onWindowSizeChange currentWidthBreakpoint= '+widthBp); AppStorage.setOrCreate('windowWidth', windowSize.width); AppStorage.setOrCreate('windowHeight', windowSize.height); if(windowSize.width > windowSize.height){ AppStorage.setOrCreate('isLandscape', true); }else{ AppStorage.setOrCreate('isLandscape', false); } // LogUtil.info('hicar onWindowSizeChange width= '+windowSize.width); // LogUtil.info( 'hicar onWindowSizeChange height= '+windowSize.height); }; onAvoidAreaChange = (data: window.AvoidAreaOptions) => { if (data.type === window.AvoidAreaType.TYPE_SYSTEM) { let topRectHeight = px2vp(data.area.topRect.height); AppStorage.setOrCreate('topRectHeight', topRectHeight); } else if (data.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) { let bottomRectHeight = px2vp(data.area.bottomRect.height); AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight); } } async onCreate(want:Want, launchParam:AbilityConstant.LaunchParam) { AppUtil.init(this.context); AppStorage.setOrCreate('context', this.context); hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onCreate'); // 注册卡片call事件监听器 this.registerWidgetCallListeners(); // 初始化统一播放器服务(与主应用共享) try { await UnifiedPlayerService.getInstance().initialize(this.context); hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService initialized successfully'); } catch (error) { hilog.error(0x0000, 'Heanup2', `❌ Failed to initialize UnifiedPlayerService: ${error}`); } // 执行卡片注册修复(异步执行,不阻塞启动) this.fixWidgetRegistrationAsync(); setTimeout(async ()=>{ this.loadDoWant(want) await this.handleParam(want) },2000) this.handleWeChatCallIfNeed(want) this.getHiCarStatus() } async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise { hilog.info(0x0000, 'Heanup2', `onNewWant, want=${JSON.stringify(want)}`); super.onNewWant(want, launchParam); this.loadDoWant(want) await this.handleParam(want) this.handleWeChatCallIfNeed(want) } private handleWeChatCallIfNeed(want: Want) { WXApi.handleWant(want, WXEventHandler) } //处理其他app点击其他应用打开播放器播放视频或者音频 loadDoWant(want: Want){ // console.info('onecold KnockController 碰一碰 want ='+JSON.stringify(want)); let uri = want.uri; if (uri == null || uri == undefined|| StrUtil.isEmpty(uri)) { console.info('uri is invalid'); return; } hilog.info(0x0000, 'Heanup2', `onCreate or onNewWant, uri=${uri}`); this.doSendEmit(uri) } //广播通知打开播放器播放视频或者音频 doSendEmit(uri:string){ setTimeout(async ()=>{ let eventData: emitter.EventData = { data: { message: uri } }; if(Utility.isMeidaByExtension(uri)){ emitter.emit({ eventId: 2 }, eventData); // 发送音频打开广播事件 }else{ emitter.emit({ eventId: 1 }, eventData); // 发送视频打开广播事件 } },300) } // 华为分享拉起接收 处理分享数据 // 1. 改造 handleParam 为异步函数,让其返回 Promise async handleParam(want: Want) { try { // 通过 await 等待异步操作完成 const data = await systemShare.getSharedData(want); const records = data.getRecords(); let uri = want.uri; for (const record of records) { if (record.uri) { uri = record.uri; this.doSendEmit(uri) break; } } } catch (error) { const businessError = error as BusinessError; console.error(`Failed: Code ${businessError.code}, ${businessError.message}`); } } onDestroy() { hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onDestroy'); // 注销卡片call事件监听器 this.unregisterWidgetCallListeners(); let types: smartMobilityCommon.SmartMobilityType[] = [smartMobilityCommon.SmartMobilityType.CAR_HOP]; // 出行连接状态回调函数 const callBack = (info: smartMobilityCommon.SmartMobilityInfo) => { hilog.info(0x0000, 'Received smart mobility info: ', JSON.stringify(info)); }; // 解注册智慧出行连接状态的监听 示例2 this.awareness.off('smartMobilityStatus', types, callBack); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageCreate'); SpiderMan.init(); AppUtil.init(this.context); // 初始化 DirectFormUpdateService 的上下文 try { import('../common/widget/DirectFormUpdateService').then((module) => { const directFormService = module.DirectFormUpdateService.getInstance(); directFormService.setAppContext(this.context); hilog.info(0x0000, 'Heanup2', 'DirectFormUpdateService context initialized'); }).catch((error: Error) => { hilog.error(0x0000, 'Heanup2', `Failed to initialize DirectFormUpdateService: ${error.message}`); }); } catch (error) { hilog.error(0x0000, 'Heanup2', `Error initializing DirectFormUpdateService: ${error}`); } //1.获取应用主窗口。 let windowClass: window.Window | null = null; windowStage.getMainWindow((err: BusinessError, data) => { windowClass = data; // LogUtil.info( 'getMainWindow = '); GlobalContext.getContext().setObject('windowClass', data); // 使用GlobalContext替代globalThis windowClass.setWindowLayoutFullScreen(true).then(() => { console.info('Succeeded in setting the window layout to full-screen mode.'); }).catch((e: BusinessError) => { console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(e)); }) // let avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM) // let topRectHeight = px2vp(avoidArea.topRect.height); // AppStorage.setOrCreate('topRectHeight', topRectHeight); let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例 let avoidArea = windowClass.getWindowAvoidArea(type); let bottomRectHeight = px2vp(avoidArea.bottomRect.height); // 获取到导航条区域的高度 AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight); type = window.AvoidAreaType.TYPE_SYSTEM; // 以状态栏避让为例 avoidArea = windowClass.getWindowAvoidArea(type); let topRectHeight = px2vp(avoidArea.topRect.height) // 获取状态栏区域高度 AppStorage.setOrCreate('topRectHeight', topRectHeight); LogUtil.info('onecold topRectHeight = '+topRectHeight); windowClass.on('avoidAreaChange', this.onAvoidAreaChange) }) AppStorage.setOrCreate('windowStage',windowStage); hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/SplashIndex', (err, data) => { if (err.code) { hilog.error(0x0000, 'Heanup2', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } //一多断点开发 windowStage.getMainWindow().then((data: window.Window) => { this.uiContext = data.getUIContext(); let widthBp = this.uiContext.getWindowWidthBreakpoint(); let heightBp = this.uiContext.getWindowHeightBreakpoint(); AppStorage.setOrCreate('currentWidthBreakpoint', widthBp); AppStorage.setOrCreate('currentHeightBreakpoint', heightBp); LogUtil.info( 'getMainWindow currentHeightBreakpoint= '+heightBp); LogUtil.info( 'getMainWindow currentWidthBreakpoint= '+widthBp); data.on('windowSizeChange', this.onWindowSizeChange); AppStorage.setOrCreate('windowWidth', data.getWindowProperties().windowRect.width); AppStorage.setOrCreate('windowHeight', data.getWindowProperties().windowRect.height); if(data.getWindowProperties().windowRect.width > data.getWindowProperties().windowRect.height){ AppStorage.setOrCreate('isLandscape', true); }else{ AppStorage.setOrCreate('isLandscape', false); } // LogUtil.info('hicar getMainWindow width= '+data.getWindowProperties().windowRect.width); // LogUtil.info( 'hicar getMainWindow height= '+data.getWindowProperties().windowRect.height); }).catch((err: BusinessError) => { console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`); }); hilog.info(0x0000, 'Heanup2', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); }); } onWindowStageDestroy() { // Main window is destroyed, release UI related resources hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageDestroy'); } onForeground() { // Ability has brought to foreground hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground'); } onBackground() { // Ability has back to background hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground'); } getHiCarStatus(){ this.awareness = smartMobilityCommon.getSmartMobilityAwareness(); // 业务类型 let types: smartMobilityCommon.SmartMobilityType[] = [smartMobilityCommon.SmartMobilityType.HICAR]; // 获取出行业务连接状态 let info = this.awareness.getSmartMobilityStatus(types[0]); hilog.info(0x0000, 'getHiCarStatus info: ', JSON.stringify(info)); if(info&&info.status==1){ AppStorage.setOrCreate('isHiCarStatus', true); }else{ AppStorage.setOrCreate('isHiCarStatus', false); } // 出行连接状态回调函数 const callBack = (info: smartMobilityCommon.SmartMobilityInfo) => { hilog.info(0x0000, 'getHiCarStatus Received smart mobility info: ', JSON.stringify(info)); if(info&&info.status==1){ AppStorage.setOrCreate('isHiCarStatus', true); }else{ AppStorage.setOrCreate('isHiCarStatus', false); } this.sendChangeEvent() }; // 注册智慧出行连接状态的监听 this.awareness.on('smartMobilityStatus', types, callBack); } //发送广播通知更新UI sendChangeEvent() { const eventData: emitter.EventData = {}; emitter.emit({ eventId: 333 }, eventData); // 发送广播通知更新doSwipBack } /** * 注册卡片call事件监听器 */ private registerWidgetCallListeners(): void { try { // 监听播放/暂停事件 this.callee.on('playPause', (data: rpc.MessageSequence) => { hilog.info(0x0000, 'Heanup2', `Widget call: playPause received`); const params: Record = JSON.parse(data.readString()) as Record; hilog.info(0x0000, 'Heanup2', `Widget playPause params: ${JSON.stringify(params)}`); // 发送播放/暂停事件到主应用 this.sendWidgetControlEvent('PLAY_PAUSE', params); return new MyParcelable(1, 'playPause_success'); }); // 监听下一首事件 this.callee.on('nextSong', (data: rpc.MessageSequence) => { hilog.info(0x0000, 'Heanup2', `Widget call: nextSong received`); const params: Record = JSON.parse(data.readString()) as Record; hilog.info(0x0000, 'Heanup2', `Widget nextSong params: ${JSON.stringify(params)}`); // 发送下一首事件到主应用 this.sendWidgetControlEvent('NEXT_SONG', params); return new MyParcelable(2, 'nextSong_success'); }); // 监听上一首事件 this.callee.on('prevSong', (data: rpc.MessageSequence) => { hilog.info(0x0000, 'Heanup2', `Widget call: prevSong received`); const params: Record = JSON.parse(data.readString()) as Record; hilog.info(0x0000, 'Heanup2', `Widget prevSong params: ${JSON.stringify(params)}`); // 发送上一首事件到主应用 this.sendWidgetControlEvent('PREV_SONG', params); return new MyParcelable(3, 'prevSong_success'); }); // 监听打开应用事件 this.callee.on('openApp', (data: rpc.MessageSequence) => { hilog.info(0x0000, 'Heanup2', `Widget call: openApp received`); const params: Record = JSON.parse(data.readString()) as Record; hilog.info(0x0000, 'Heanup2', `Widget openApp params: ${JSON.stringify(params)}`); // 发送打开应用事件到主应用 this.sendWidgetControlEvent('OPEN_APP', params); return new MyParcelable(4, 'openApp_success'); }); hilog.info(0x0000, 'Heanup2', 'Widget call listeners registered successfully'); } catch (err) { hilog.error(0x0000, 'Heanup2', `Failed to register widget call listeners: ${JSON.stringify(err as BusinessError)}`); } } /** * 注销卡片call事件监听器 */ private unregisterWidgetCallListeners(): void { try { this.callee.off('playPause'); this.callee.off('nextSong'); this.callee.off('prevSong'); // this.callee.off('openApp'); // this.callee.off('playByAction'); // this.callee.off('collectAction'); // this.callee.off('requestUpdatePlayCard'); hilog.info(0x0000, 'Heanup2', 'Widget call listeners unregistered successfully'); } catch (err) { hilog.error(0x0000, 'Heanup2', `Failed to unregister widget call listeners: ${JSON.stringify(err as BusinessError)}`); } } /** * 发送卡片控制事件到主应用 */ private async sendWidgetControlEvent(command: string, params: Record): Promise { try { hilog.info(0x0000, 'Heanup2', `🎵 Processing widget control command: ${command}`); // 获取UnifiedPlayerService实例 const unifiedService = UnifiedPlayerService.getInstance(); // 确保服务已经初始化 if (!unifiedService) { hilog.error(0x0000, 'Heanup2', '❌ UnifiedPlayerService not available'); return; } // 在处理卡片控制前,确保服务完全初始化 try { await unifiedService.initialize(this.context); hilog.info(0x0000, 'Heanup2', '🔄 UnifiedPlayerService re-initialized for widget command'); } catch (error) { hilog.error(0x0000, 'Heanup2', `❌ Failed to re-initialize UnifiedPlayerService: ${error}`); } // 检查初始化状态 const currentState = unifiedService.getCurrentState(); hilog.info(0x0000, 'Heanup2', `🎵 Widget command - Service state: isPlaying=${currentState.isPlaying}, currentIndex=${currentState.currentIndex}`); // 根据命令执行相应的播放控制 switch (command) { case 'PLAY_PAUSE': if (currentState.isPlaying) { unifiedService.pause(); hilog.info(0x0000, 'Heanup2', '✅ Widget command: Paused playback'); } else { unifiedService.startPlayOrResumePlay(); hilog.info(0x0000, 'Heanup2', '✅ Widget command: Started/resumed playback'); } break; case 'NEXT_SONG': await unifiedService.playNext(); hilog.info(0x0000, 'Heanup2', '✅ Widget command: Next song'); break; case 'PREV_SONG': await unifiedService.playPrevious(); hilog.info(0x0000, 'Heanup2', '✅ Widget command: Previous song'); break; case 'OPEN_APP': hilog.info(0x0000, 'Heanup2', '✅ Widget command: Open app (handled by UI)'); break; default: hilog.warn(0x0000, 'Heanup2', `❓ Unknown widget command: ${command}`); break; } hilog.info(0x0000, 'Heanup2', `✅ Widget control command processed: ${command}`); } catch (error) { hilog.error(0x0000, 'Heanup2', `❌ Failed to process widget control command: ${error}`); } } /** * 异步执行卡片注册修复 */ private async fixWidgetRegistrationAsync(): Promise { // 延迟3秒执行,确保应用完全启动 setTimeout(async () => { try { const widgetFix = WidgetRegistrationFix.getInstance(); await widgetFix.fixWidgetRegistration(this.context); } catch (error) { hilog.error(0x0000, 'Heanup2', `❌ 卡片注册修复失败: ${error}`); } }, 3000); } }