/** * 应用主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 { DemoConstants } from './DemoConstants'; import { EventConstants } from '../common/constants/EventConstants'; import { Utility } from '../common/util/Utility'; import { WXApi, WXEventHandler } from '../common/util/WXApiWrap'; import { systemShare } from '@kit.ShareKit'; import Logger from '../common/util/Logger'; import statusBarManager from '@hms.pcService.statusBarManager'; import StatusBarViewExtensionAbility from '@hms.pcService.StatusBarViewExtensionAbility'; import { SpiderMan } from '@simplepeng/spider-man'; import { smartMobilityCommon } from '@kit.CarKit'; import { url } from '@kit.ArkTS'; import { display } from '@kit.ArkUI'; /** * 主Ability类,继承自UIAbility * 负责: * - 应用初始化 * - 窗口管理 * - 事件分发 */ export default class EntryAbility extends UIAbility { // UI上下文对象,用于获取窗口信息 private uiContext?: UIContext; // private awareness: smartMobilityCommon.SmartMobilityAwareness = smartMobilityCommon.getSmartMobilityAwareness(); private awareness: smartMobilityCommon.SmartMobilityAwareness|undefined = canIUse("SystemCapability.CarService.DistributedEngine")?smartMobilityCommon.getSmartMobilityAwareness():undefined; /** * 窗口尺寸变化回调函数 * @param windowSize 新的窗口尺寸对象 * 功能: * 1. 获取最新的窗口断点尺寸 * 2. 更新AppStorage中的尺寸状态 * 3. 记录尺寸变化日志 */ private onWindowSizeChange: (windowSize: window.Size) => void = async (windowSize: window.Size) => { // 获取宽度断点并更新全局状态 let widthBp: WidthBreakpoint = this.uiContext!.getWindowWidthBreakpoint(); AppStorage.setOrCreate('currentWidthBreakpoint', widthBp); // 获取高度断点并更新全局状态 let heightBp: HeightBreakpoint = 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); } } onDisplayIdChange=(displayId: number)=> { let curDisplay = display.getDisplayByIdSync(displayId); console.info('twocold curDisplay 2 = '+curDisplay.name); if(curDisplay.name =='HiCar'||curDisplay.name =='SuperLauncher'){ AppStorage.setOrCreate('curDisplayIsHiCar', true); }else{ AppStorage.setOrCreate('curDisplayIsHiCar', false); } } async onCreate(want:Want, launchParam:AbilityConstant.LaunchParam) { AppStorage.setOrCreate('context', this.context); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // 初始化WebDAV管理器 this.initWebDAV(); setTimeout(async ()=>{ this.loadDoWant(want) await this.handleParam(want) },2000) this.handleWeChatCallIfNeed(want) this.getHiCarStatus() } /** * 初始化WebDAV管理器 * 功能: * 1. 设置Context * 2. 初始化数据库和Preferences * 3. 创建WebDAV数据库表 * 4. 加载WebDAV账户信息 */ private async initWebDAV() { try { Logger.info('heanup EntryAbility', '开始初始化WebDAV管理器'); // 1. 初始化DataBaseUtil const DataBaseUtil = (await import('../common/util/DataBaseUtil')).DataBaseUtil; DataBaseUtil.getInstance().setContext(this.context); // 2. 初始化PreferencesUtil // const PreferencesUtil = (await import('../common/util/PreferencesUtil')).default; // PreferencesUtil.getInstance().setContext(this.context); // 3. 初始化RemoteDriveManager const RemoteDriveManagerModule = await import('../common/util/RemoteDriveManager'); const webdavManager = RemoteDriveManagerModule.RemoteDriveManager.getInstance(); webdavManager.setContext(this.context); // 4. 创建WebDAV数据库表 await webdavManager.createWebDavTableInDB(); // 5. 从数据库加载账户 await webdavManager.queryWebDavAccountsFromDB(); // 6. 加载历史数据(如果有迁移需求) await webdavManager.loadInfo(); Logger.info('heanup EntryAbility', 'WebDAV管理器初始化成功'); } catch (error) { Logger.error('heanup EntryAbility', `WebDAV管理器初始化失败: ${error}`); } } async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise { hilog.info(0x0000, 'testTag', `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, 'testTag', `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: EventConstants.EVENT_AUDIO_OPEN }, eventData); // 发送音频打开广播事件 }else{ emitter.emit({ eventId: EventConstants.EVENT_VIDEO_OPEN }, 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() { try { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); if(this.awareness){ 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); } }catch (error) { console.error(`Failed to getHiCarStatus: ${error.code}, message: ${error.message}`); } } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); SpiderMan.init(); AppUtil.init(this.context); //1.获取应用主窗口。 let windowClass: window.Window | null = null; windowStage.getMainWindow((err: BusinessError, data) => { windowClass = data; // LogUtil.info( 'getMainWindow = '); globalThis.windowClass = data // 赋值给全局变量windowClass let curDisplay = display.getDisplayByIdSync(windowClass.getWindowProperties().displayId); console.info('twocold curDisplay = '+curDisplay.name); if(curDisplay.name =='HiCar'||curDisplay.name =='SuperLauncher'){ AppStorage.setOrCreate('curDisplayIsHiCar', true); }else{ AppStorage.setOrCreate('curDisplayIsHiCar', false); } 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) windowClass.on('displayIdChange', this.onDisplayIdChange) }) AppStorage.setOrCreate('windowStage',windowStage); GlobalContext.getContext().setObject('windowClass',windowClass) hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/SplashIndex', (err, data) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } //一多断点开发 windowStage.getMainWindow().then((data: window.Window) => { this.uiContext = data.getUIContext(); let widthBp: WidthBreakpoint = this.uiContext.getWindowWidthBreakpoint(); let heightBp: HeightBreakpoint = 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, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); }); DemoConstants.windowStage = windowStage } onWindowStageDestroy() { // Main window is destroyed, release UI related resources hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); } onForeground() { // Ability has brought to foreground hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); } onBackground() { // Ability has back to background hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); } getHiCarStatus(){ try { if (!this.awareness){ this.awareness=canIUse("SystemCapability.CarService.DistributedEngine")?smartMobilityCommon.getSmartMobilityAwareness():undefined; } console.log('enter getHiCarStatus,awareness:'+JSON.stringify(this.awareness)); if(this.awareness){ console.log('enter awareness'); // 业务类型 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); const eventData: emitter.EventData = {}; emitter.emit({ eventId: EventConstants.EVENT_PLAY_PAUSE }, eventData); // 发送广播通知更新doSwipBack } this.sendChangeEvent() }; // 注册智慧出行连接状态的监听 this.awareness.on('smartMobilityStatus', types, callBack); }else{ AppStorage.setOrCreate('isHiCarStatus', false); } }catch (error) { console.error(`Failed to getHiCarStatus: ${error.code}, message: ${error.message}`); } } //发送广播通知更新UI sendChangeEvent() { const eventData: emitter.EventData = {}; emitter.emit({ eventId: EventConstants.EVENT_SETTING_UPDATE }, eventData); // 发送广播通知更新doSwipBack } }