EntryAbility.ets 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. /**
  2. * 应用主Ability入口文件
  3. * 功能:
  4. * 1. 管理应用生命周期
  5. * 2. 处理窗口创建和尺寸变化
  6. * 3. 响应外部调用请求
  7. * 4. 全局状态管理
  8. */
  9. import UIAbility from '@ohos.app.ability.UIAbility';
  10. import hilog from '@ohos.hilog';
  11. import window from '@ohos.window';
  12. import { AbilityConstant, Want } from '@kit.AbilityKit';
  13. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  14. import { AppUtil, ArrayUtil, GlobalContext, LogUtil, StrUtil } from '@pura/harmony-utils';
  15. import { rpc } from '@kit.IPCKit';
  16. import { Utility } from '../common/util/Utility';
  17. import { WXApi, WXEventHandler } from '../common/util/WXApiWrap';
  18. import { UnifiedPlayerService } from '../common/service/UnifiedPlayerService';
  19. import { WidgetRegistrationFix } from '../common/widget/WidgetRegistrationFix';
  20. import { systemShare } from '@kit.ShareKit';
  21. import { CustomCrashHandler } from '../common/utils/CustomCrashHandler';
  22. import { smartMobilityCommon } from '@kit.CarKit';
  23. import { url } from '@kit.ArkTS';
  24. import { display } from '@kit.ArkUI';
  25. /**
  26. * 播放状态广播数据接口
  27. */
  28. interface PlayStateBroadcast {
  29. isPlaying: boolean;
  30. isPaused: boolean;
  31. isLoading: boolean;
  32. }
  33. interface SongBroadcast {
  34. id: string;
  35. title: string;
  36. artist: string;
  37. album: string;
  38. coverImagePath: string;
  39. duration: number;
  40. }
  41. interface ProgressBroadcast {
  42. currentPosition: number;
  43. duration: number;
  44. percentage: number;
  45. currentTimeText: string;
  46. totalTimeText: string;
  47. }
  48. interface PlaylistBroadcast {
  49. hasNext: boolean;
  50. hasPrevious: boolean;
  51. currentIndex: number;
  52. totalCount: number;
  53. }
  54. interface BroadcastData {
  55. playState: PlayStateBroadcast;
  56. currentSong: SongBroadcast;
  57. progress: ProgressBroadcast;
  58. playlist: PlaylistBroadcast;
  59. }
  60. interface PublishInfo {
  61. data: string;
  62. }
  63. interface EventDataWrapper {
  64. data: BroadcastData;
  65. }
  66. /**
  67. * RPC通信返回类型的实现,用于RPC通信数据序列化和反序列化
  68. */
  69. class MyParcelable implements rpc.Parcelable {
  70. num: number;
  71. str: string;
  72. constructor(num: number, str: string) {
  73. this.num = num;
  74. this.str = str;
  75. }
  76. marshalling(messageSequence: rpc.MessageSequence): boolean {
  77. messageSequence.writeInt(this.num);
  78. messageSequence.writeString(this.str);
  79. return true;
  80. }
  81. unmarshalling(messageSequence: rpc.MessageSequence): boolean {
  82. this.num = messageSequence.readInt();
  83. this.str = messageSequence.readString();
  84. return true;
  85. }
  86. }
  87. /**
  88. * 主Ability类,继承自UIAbility
  89. * 负责:
  90. * - 应用初始化
  91. * - 窗口管理
  92. * - 事件分发
  93. */
  94. export default class EntryAbility extends UIAbility {
  95. // UI上下文对象,用于获取窗口信息
  96. private uiContext?: UIContext;
  97. // private awareness: smartMobilityCommon.SmartMobilityAwareness = smartMobilityCommon.getSmartMobilityAwareness();
  98. private awareness: smartMobilityCommon.SmartMobilityAwareness|undefined = canIUse("SystemCapability.SmartOptimizer.SmartMobility")?smartMobilityCommon.getSmartMobilityAwareness():undefined;
  99. /**
  100. * 窗口尺寸变化回调函数
  101. * @param windowSize 新的窗口尺寸对象
  102. * 功能:
  103. * 1. 获取最新的窗口断点尺寸
  104. * 2. 更新AppStorage中的尺寸状态
  105. * 3. 记录尺寸变化日志
  106. */
  107. private onWindowSizeChange: (windowSize: window.Size) => void = async (windowSize: window.Size) => {
  108. // 获取宽度断点并更新全局状态
  109. let widthBp = this.uiContext!.getWindowWidthBreakpoint();
  110. AppStorage.setOrCreate('currentWidthBreakpoint', widthBp);
  111. // 获取高度断点并更新全局状态
  112. let heightBp = this.uiContext!.getWindowHeightBreakpoint();
  113. AppStorage.setOrCreate('currentHeightBreakpoint', heightBp);
  114. // 记录尺寸变化日志
  115. // LogUtil.info('pura onWindowSizeChange currentHeightBreakpoint= '+heightBp);
  116. // LogUtil.info( 'pura onWindowSizeChange currentWidthBreakpoint= '+widthBp);
  117. AppStorage.setOrCreate('windowWidth', windowSize.width);
  118. AppStorage.setOrCreate('windowHeight', windowSize.height);
  119. if(windowSize.width > windowSize.height){
  120. AppStorage.setOrCreate('isLandscape', true);
  121. }else{
  122. AppStorage.setOrCreate('isLandscape', false);
  123. }
  124. // LogUtil.info('hicar onWindowSizeChange width= '+windowSize.width);
  125. // LogUtil.info( 'hicar onWindowSizeChange height= '+windowSize.height);
  126. };
  127. onAvoidAreaChange = (data: window.AvoidAreaOptions) => {
  128. if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
  129. let topRectHeight = px2vp(data.area.topRect.height);
  130. AppStorage.setOrCreate('topRectHeight', topRectHeight);
  131. } else if (data.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
  132. let bottomRectHeight = px2vp(data.area.bottomRect.height);
  133. AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
  134. }
  135. }
  136. async onCreate(want:Want, launchParam:AbilityConstant.LaunchParam) {
  137. AppUtil.init(this.context);
  138. AppStorage.setOrCreate('context', this.context);
  139. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onCreate');
  140. // 注册卡片call事件监听器
  141. this.registerWidgetCallListeners();
  142. // 异步初始化统一播放器服务,避免阻塞生命周期
  143. this.initializePlayerServiceAsync();
  144. // 执行卡片注册修复(异步执行,不阻塞启动)
  145. this.fixWidgetRegistrationAsync();
  146. // 异步处理Want参数,避免阻塞生命周期
  147. this.handleWantAsync(want);
  148. this.handleWeChatCallIfNeed(want)
  149. this.getHiCarStatus()
  150. }
  151. async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
  152. hilog.info(0x0000, 'Heanup2', `onNewWant, want=${JSON.stringify(want)}`);
  153. super.onNewWant(want, launchParam);
  154. // 异步处理Want参数,避免阻塞生命周期
  155. this.handleWantAsync(want);
  156. this.handleWeChatCallIfNeed(want)
  157. }
  158. private handleWeChatCallIfNeed(want: Want) {
  159. WXApi.handleWant(want, WXEventHandler)
  160. }
  161. //处理其他app点击其他应用打开播放器播放视频或者音频
  162. loadDoWant(want: Want){
  163. // console.info('onecold KnockController 碰一碰 want ='+JSON.stringify(want));
  164. let uri = want.uri;
  165. if (uri == null || uri == undefined|| StrUtil.isEmpty(uri)) {
  166. console.info('uri is invalid');
  167. return;
  168. }
  169. hilog.info(0x0000, 'Heanup2', `onCreate or onNewWant, uri=${uri}`);
  170. this.doSendEmit(uri)
  171. }
  172. //广播通知打开播放器播放视频或者音频
  173. doSendEmit(uri:string){
  174. setTimeout(async ()=>{
  175. let eventData: emitter.EventData = {
  176. data: {
  177. message: uri
  178. }
  179. };
  180. if(Utility.isMeidaByExtension(uri)){
  181. emitter.emit({ eventId: 2 }, eventData); // 发送音频打开广播事件
  182. }else{
  183. emitter.emit({ eventId: 1 }, eventData); // 发送视频打开广播事件
  184. }
  185. },300)
  186. }
  187. // 华为分享拉起接收 处理分享数据
  188. // 1. 改造 handleParam 为异步函数,让其返回 Promise
  189. async handleParam(want: Want) {
  190. try {
  191. // 通过 await 等待异步操作完成
  192. const data = await systemShare.getSharedData(want);
  193. const records = data.getRecords();
  194. let uri = want.uri;
  195. for (const record of records) {
  196. if (record.uri) {
  197. uri = record.uri;
  198. this.doSendEmit(uri)
  199. break;
  200. }
  201. }
  202. } catch (error) {
  203. const businessError = error as BusinessError;
  204. console.error(`Failed: Code ${businessError.code}, ${businessError.message}`);
  205. }
  206. }
  207. onDestroy() {
  208. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onDestroy');
  209. // 关键修复:在APP销毁时保存播放器状态
  210. try {
  211. const unifiedPlayerService = UnifiedPlayerService.getInstance();
  212. if (unifiedPlayerService) {
  213. // 确保在APP被杀掉时保存当前播放状态
  214. unifiedPlayerService.release();
  215. hilog.info(0x0000, 'Heanup2', 'UnifiedPlayerService released and state saved on app destroy');
  216. }
  217. } catch (error) {
  218. hilog.error(0x0000, 'Heanup2', `Failed to release UnifiedPlayerService: ${error}`);
  219. }
  220. // 注销卡片call事件监听器
  221. this.unregisterWidgetCallListeners();
  222. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  223. if(this.awareness){
  224. let types: smartMobilityCommon.SmartMobilityType[] = [smartMobilityCommon.SmartMobilityType.CAR_HOP];
  225. // 出行连接状态回调函数
  226. const callBack = (info: smartMobilityCommon.SmartMobilityInfo) => {
  227. hilog.info(0x0000, 'Received smart mobility info: ', JSON.stringify(info));
  228. };
  229. // 解注册智慧出行连接状态的监听 示例2
  230. this.awareness.off('smartMobilityStatus', types, callBack);
  231. }
  232. }
  233. onWindowStageCreate(windowStage: window.WindowStage) {
  234. // Main window is created, set main page for this ability
  235. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageCreate');
  236. // 使用自定义崩溃处理器替代 SpiderMan.init()
  237. // SpiderMan.init();
  238. CustomCrashHandler.init();
  239. AppUtil.init(this.context);
  240. //1.获取应用主窗口。
  241. let windowClass: window.Window | null = null;
  242. windowStage.getMainWindow((err: BusinessError, data) => {
  243. windowClass = data;
  244. // LogUtil.info( 'getMainWindow = ');
  245. GlobalContext.getContext().setObject('windowClass', data); // 使用GlobalContext替代globalThis
  246. let curDisplay = display.getDisplayByIdSync(windowClass.getWindowProperties().displayId);
  247. console.info('twocold curDisplay = '+curDisplay.name);
  248. if(curDisplay.name =='HiCar'||curDisplay.name =='SuperLauncher'){
  249. AppStorage.setOrCreate('curDisplayIsHiCar', true);
  250. }else{
  251. AppStorage.setOrCreate('curDisplayIsHiCar', false);
  252. }
  253. windowClass.setWindowLayoutFullScreen(true).then(() => {
  254. console.info('Succeeded in setting the window layout to full-screen mode.');
  255. }).catch((e: BusinessError) => {
  256. console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(e));
  257. })
  258. // let avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
  259. // let topRectHeight = px2vp(avoidArea.topRect.height);
  260. // AppStorage.setOrCreate('topRectHeight', topRectHeight);
  261. let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
  262. let avoidArea = windowClass.getWindowAvoidArea(type);
  263. let bottomRectHeight = px2vp(avoidArea.bottomRect.height); // 获取到导航条区域的高度
  264. AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
  265. type = window.AvoidAreaType.TYPE_SYSTEM; // 以状态栏避让为例
  266. avoidArea = windowClass.getWindowAvoidArea(type);
  267. let topRectHeight = px2vp(avoidArea.topRect.height) // 获取状态栏区域高度
  268. AppStorage.setOrCreate('topRectHeight', topRectHeight);
  269. LogUtil.info('onecold topRectHeight = '+topRectHeight);
  270. windowClass.on('avoidAreaChange', this.onAvoidAreaChange)
  271. })
  272. AppStorage.setOrCreate('windowStage',windowStage);
  273. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageCreate');
  274. windowStage.loadContent('pages/SplashIndex', (err, data) => {
  275. if (err.code) {
  276. hilog.error(0x0000, 'Heanup2', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  277. return;
  278. }
  279. //一多断点开发
  280. windowStage.getMainWindow().then((data: window.Window) => {
  281. this.uiContext = data.getUIContext();
  282. let widthBp = this.uiContext.getWindowWidthBreakpoint();
  283. let heightBp = this.uiContext.getWindowHeightBreakpoint();
  284. AppStorage.setOrCreate('currentWidthBreakpoint', widthBp);
  285. AppStorage.setOrCreate('currentHeightBreakpoint', heightBp);
  286. LogUtil.info( 'getMainWindow currentHeightBreakpoint= '+heightBp);
  287. LogUtil.info( 'getMainWindow currentWidthBreakpoint= '+widthBp);
  288. data.on('windowSizeChange', this.onWindowSizeChange);
  289. AppStorage.setOrCreate('windowWidth', data.getWindowProperties().windowRect.width);
  290. AppStorage.setOrCreate('windowHeight', data.getWindowProperties().windowRect.height);
  291. if(data.getWindowProperties().windowRect.width > data.getWindowProperties().windowRect.height){
  292. AppStorage.setOrCreate('isLandscape', true);
  293. }else{
  294. AppStorage.setOrCreate('isLandscape', false);
  295. }
  296. // LogUtil.info('hicar getMainWindow width= '+data.getWindowProperties().windowRect.width);
  297. // LogUtil.info( 'hicar getMainWindow height= '+data.getWindowProperties().windowRect.height);
  298. }).catch((err: BusinessError) => {
  299. console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
  300. });
  301. hilog.info(0x0000, 'Heanup2', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
  302. });
  303. }
  304. onWindowStageDestroy() {
  305. // Main window is destroyed, release UI related resources
  306. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onWindowStageDestroy');
  307. }
  308. onForeground() {
  309. // Ability has brought to foreground
  310. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground start');
  311. // 异步处理前台逻辑,避免阻塞生命周期
  312. setTimeout(() => {
  313. this.handleForegroundAsync();
  314. }, 10);
  315. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground end');
  316. }
  317. onBackground() {
  318. // Ability has back to background
  319. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground start');
  320. // 异步处理后台逻辑,避免阻塞生命周期
  321. setTimeout(() => {
  322. this.handleBackgroundAsync();
  323. }, 10);
  324. hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground end');
  325. }
  326. getHiCarStatus(){
  327. if(this.awareness){
  328. // this.awareness = smartMobilityCommon.getSmartMobilityAwareness();
  329. // 业务类型
  330. let types: smartMobilityCommon.SmartMobilityType[] = [smartMobilityCommon.SmartMobilityType.HICAR];
  331. // 获取出行业务连接状态
  332. let info = this.awareness.getSmartMobilityStatus(types[0]);
  333. hilog.info(0x0000, 'getHiCarStatus info: ', JSON.stringify(info));
  334. if(info&&info.status==1){
  335. AppStorage.setOrCreate('isHiCarStatus', true);
  336. }else{
  337. AppStorage.setOrCreate('isHiCarStatus', false);
  338. }
  339. // 出行连接状态回调函数
  340. const callBack = (info: smartMobilityCommon.SmartMobilityInfo) => {
  341. hilog.info(0x0000, 'getHiCarStatus Received smart mobility info: ', JSON.stringify(info));
  342. if(info&&info.status==1){
  343. AppStorage.setOrCreate('isHiCarStatus', true);
  344. }else{
  345. AppStorage.setOrCreate('isHiCarStatus', false);
  346. }
  347. this.sendChangeEvent()
  348. };
  349. // 注册智慧出行连接状态的监听
  350. this.awareness.on('smartMobilityStatus', types, callBack);
  351. }else{
  352. AppStorage.setOrCreate('isHiCarStatus', false);
  353. }
  354. }
  355. //发送广播通知更新UI
  356. sendChangeEvent() {
  357. const eventData: emitter.EventData = {};
  358. emitter.emit({ eventId: 333 }, eventData); // 发送广播通知更新doSwipBack
  359. }
  360. /**
  361. * 注册卡片call事件监听器(增强版本:服务就绪检查)
  362. */
  363. private registerWidgetCallListeners(): void {
  364. try {
  365. // 监听播放/暂停事件
  366. this.callee.on('playPause', (data: rpc.MessageSequence) => {
  367. try {
  368. const params: Record<string, Object> = JSON.parse(data.readString()) as Record<string, Object>;
  369. hilog.info(0x0000, 'Heanup2', `🎵 Widget call: playPause received`);
  370. // 异步发送播放/暂停事件到主应用(包含服务就绪检查)
  371. this.sendWidgetControlEvent('PLAY_PAUSE', params).catch((error: Error) => {
  372. hilog.error(0x0000, 'Heanup2', `❌ playPause async error: ${error}`);
  373. });
  374. return new MyParcelable(1, 'playPause_success');
  375. } catch (error) {
  376. hilog.error(0x0000, 'Heanup2', `❌ playPause handler error: ${error}`);
  377. return new MyParcelable(-1, 'playPause_error');
  378. }
  379. });
  380. // 监听下一首事件
  381. this.callee.on('nextSong', (data: rpc.MessageSequence) => {
  382. try {
  383. hilog.info(0x0000, 'Heanup2', `🎵 Widget call: nextSong received`);
  384. const params: Record<string, Object> = JSON.parse(data.readString()) as Record<string, Object>;
  385. hilog.info(0x0000, 'Heanup2', `Widget nextSong params: ${JSON.stringify(params)}`);
  386. // 异步发送下一首事件到主应用(包含服务就绪检查)
  387. this.sendWidgetControlEvent('NEXT_SONG', params).catch((error: Error) => {
  388. hilog.error(0x0000, 'Heanup2', `❌ nextSong async error: ${error}`);
  389. });
  390. return new MyParcelable(2, 'nextSong_success');
  391. } catch (error) {
  392. hilog.error(0x0000, 'Heanup2', `❌ nextSong handler error: ${error}`);
  393. return new MyParcelable(-2, 'nextSong_error');
  394. }
  395. });
  396. // 监听上一首事件
  397. this.callee.on('prevSong', (data: rpc.MessageSequence) => {
  398. try {
  399. hilog.info(0x0000, 'Heanup2', `🎵 Widget call: prevSong received`);
  400. const params: Record<string, Object> = JSON.parse(data.readString()) as Record<string, Object>;
  401. hilog.info(0x0000, 'Heanup2', `Widget prevSong params: ${JSON.stringify(params)}`);
  402. // 异步发送上一首事件到主应用(包含服务就绪检查)
  403. this.sendWidgetControlEvent('PREV_SONG', params).catch((error: Error) => {
  404. hilog.error(0x0000, 'Heanup2', `❌ prevSong async error: ${error}`);
  405. });
  406. return new MyParcelable(3, 'prevSong_success');
  407. } catch (error) {
  408. hilog.error(0x0000, 'Heanup2', `❌ prevSong handler error: ${error}`);
  409. return new MyParcelable(-3, 'prevSong_error');
  410. }
  411. });
  412. // 监听打开应用事件
  413. this.callee.on('openApp', (data: rpc.MessageSequence) => {
  414. try {
  415. hilog.info(0x0000, 'Heanup2', `🎵 Widget call: openApp received`);
  416. const params: Record<string, Object> = JSON.parse(data.readString()) as Record<string, Object>;
  417. hilog.info(0x0000, 'Heanup2', `Widget openApp params: ${JSON.stringify(params)}`);
  418. // 异步发送打开应用事件到主应用
  419. this.sendWidgetControlEvent('OPEN_APP', params).catch((error: Error) => {
  420. hilog.error(0x0000, 'Heanup2', `❌ openApp async error: ${error}`);
  421. });
  422. return new MyParcelable(4, 'openApp_success');
  423. } catch (error) {
  424. hilog.error(0x0000, 'Heanup2', `❌ openApp handler error: ${error}`);
  425. return new MyParcelable(-4, 'openApp_error');
  426. }
  427. });
  428. hilog.info(0x0000, 'Heanup2', '🎵 Widget call listeners registered successfully (Enhanced)');
  429. } catch (err) {
  430. hilog.error(0x0000, 'Heanup2', `❌ Failed to register widget call listeners: ${JSON.stringify(err as BusinessError)}`);
  431. }
  432. }
  433. /**
  434. * 注销卡片call事件监听器
  435. */
  436. private unregisterWidgetCallListeners(): void {
  437. try {
  438. this.callee.off('playPause');
  439. this.callee.off('nextSong');
  440. this.callee.off('prevSong');
  441. // this.callee.off('openApp');
  442. // this.callee.off('playByAction');
  443. // this.callee.off('collectAction');
  444. // this.callee.off('requestUpdatePlayCard');
  445. hilog.info(0x0000, 'Heanup2', 'Widget call listeners unregistered successfully');
  446. } catch (err) {
  447. hilog.error(0x0000, 'Heanup2', `Failed to unregister widget call listeners: ${JSON.stringify(err as BusinessError)}`);
  448. }
  449. }
  450. /**
  451. * 发送卡片控制事件到主应用(增强版本,确保服务已初始化)
  452. */
  453. private async sendWidgetControlEvent(command: string, params: Record<string, Object>): Promise<void> {
  454. try {
  455. hilog.info(0x0000, 'Heanup2', `🎵 收到桌面卡片指令: ${command}`);
  456. // 获取UnifiedPlayerService实例
  457. const unifiedService = UnifiedPlayerService.getInstance();
  458. // 确保服务已经初始化
  459. if (!unifiedService) {
  460. hilog.error(0x0000, 'Heanup2', '❌ UnifiedPlayerService 未初始化');
  461. return;
  462. }
  463. // 获取详细的服务就绪状态信息
  464. const readinessInfo = unifiedService.getServiceReadinessInfo();
  465. hilog.info(0x0000, 'Heanup2', `🔍 Service readiness: ${JSON.stringify(readinessInfo.details)}`);
  466. // 智能等待服务完全就绪(多级检查)
  467. hilog.info(0x0000, 'Heanup2', '🔄 检查服务就绪状态...');
  468. let ready = await this.waitForServiceReady(unifiedService);
  469. if (ready) {
  470. hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService 已就绪');
  471. } else {
  472. hilog.warn(0x0000, 'Heanup2', '⚠️ UnifiedPlayerService 未完全就绪,尝试执行基础操作');
  473. // 检查是否至少可以进行基础操作
  474. if (!unifiedService.isAllServicesReady()) {
  475. const finalReadinessInfo = unifiedService.getServiceReadinessInfo();
  476. hilog.error(0x0000, 'Heanup2', `❌ 基础服务未就绪,无法执行操作: ${JSON.stringify(finalReadinessInfo.details)}`);
  477. return;
  478. }
  479. }
  480. // 检查初始化状态
  481. const currentState = unifiedService.getCurrentState();
  482. const playlist = unifiedService.getPlaylist();
  483. hilog.info(0x0000, 'Heanup2', `🎵 Widget command - Service state: isPlaying=${currentState.isPlaying}, currentIndex=${currentState.currentIndex}, playlistSize=${playlist.length}`);
  484. // 对于播放控制操作,检查是否有可播放内容
  485. if ((command === 'PLAY_PAUSE' || command === 'NEXT_SONG' || command === 'PREV_SONG') && playlist.length === 0) {
  486. hilog.warn(0x0000, 'Heanup2', '⚠️ 播放列表为空,尝试强制数据恢复');
  487. // 强制触发数据恢复
  488. await this.forceDataRestoration(unifiedService);
  489. // 重新检查播放列表
  490. const updatedPlaylist = unifiedService.getPlaylist();
  491. if (updatedPlaylist.length === 0) {
  492. hilog.warn(0x0000, 'Heanup2', '⚠️ 强制数据恢复后播放列表仍为空,无法执行播放控制操作');
  493. return;
  494. }
  495. hilog.info(0x0000, 'Heanup2', `✅ 强制数据恢复完成,播放列表大小: ${updatedPlaylist.length}`);
  496. }
  497. // 根据命令执行相应的播放控制
  498. switch (command) {
  499. case 'PLAY_PAUSE':
  500. // 获取卡片传递的当前显示状态
  501. const widgetIsPlaying = params['widgetIsPlaying'] as boolean;
  502. const hasWidgetState = widgetIsPlaying !== undefined;
  503. // 获取服务内部状态
  504. const latestState = unifiedService.getCurrentState();
  505. hilog.info(0x0000, 'Heanup2', `🎵 卡片显示状态: isPlaying=${widgetIsPlaying} (有效: ${hasWidgetState})`);
  506. hilog.info(0x0000, 'Heanup2', `🎵 服务内部状态: isPlaying=${latestState.isPlaying}`);
  507. if (hasWidgetState) {
  508. // 新逻辑:根据卡片显示的状态来决定操作
  509. // - 如果卡片显示播放按钮(widgetIsPlaying=false),则执行播放操作
  510. // - 如果卡片显示暂停按钮(widgetIsPlaying=true),则执行暂停操作
  511. if (widgetIsPlaying) {
  512. // 卡片显示暂停按钮,用户点击要暂停
  513. await unifiedService.pause();
  514. hilog.info(0x0000, 'Heanup2', '✅ 卡片操作:暂停播放');
  515. } else {
  516. // 卡片显示播放按钮,用户点击要播放
  517. hilog.info(0x0000, 'Heanup2', '🔄 卡片操作:开始播放');
  518. await unifiedService.startPlayOrResumePlay();
  519. hilog.info(0x0000, 'Heanup2', '✅ 卡片操作:开始播放');
  520. }
  521. } else {
  522. // 向后兼容:使用原来的逻辑(根据服务内部状态)
  523. hilog.info(0x0000, 'Heanup2', '⚠️ 使用向后兼容模式(基于服务状态)');
  524. if (latestState.isPlaying) {
  525. await unifiedService.pause();
  526. hilog.info(0x0000, 'Heanup2', '✅ 兼容模式:暂停播放');
  527. } else {
  528. hilog.info(0x0000, 'Heanup2', '🔄 兼容模式:开始播放');
  529. await unifiedService.startPlayOrResumePlay();
  530. hilog.info(0x0000, 'Heanup2', '✅ 兼容模式:开始播放');
  531. }
  532. }
  533. break;
  534. case 'NEXT_SONG':
  535. await unifiedService.playNext();
  536. hilog.info(0x0000, 'Heanup2', '✅ Widget command: Next song');
  537. break;
  538. case 'PREV_SONG':
  539. await unifiedService.playPrevious();
  540. hilog.info(0x0000, 'Heanup2', '✅ Widget command: Previous song');
  541. break;
  542. case 'OPEN_APP':
  543. hilog.info(0x0000, 'Heanup2', '✅ Widget command: Open app (handled by UI)');
  544. break;
  545. default:
  546. hilog.warn(0x0000, 'Heanup2', `❓ Unknown widget command: ${command}`);
  547. break;
  548. }
  549. // 操作完成后,广播最新状态给主应用UI和桌面卡片
  550. setTimeout(() => {
  551. this.broadcastCurrentPlayerState();
  552. hilog.info(0x0000, 'Heanup2', '📡 桌面卡片操作后广播状态更新');
  553. // 同时触发UnifiedPlayerService的状态广播,确保所有监听器都能收到更新
  554. try {
  555. unifiedService.broadcastCurrentState();
  556. } catch (error) {
  557. hilog.error(0x0000, 'Heanup2', `❌ 触发服务状态广播失败: ${error}`);
  558. }
  559. }, 100); // 短延迟,确保操作完全完成
  560. hilog.info(0x0000, 'Heanup2', `✅ Widget control command processed: ${command}`);
  561. } catch (error) {
  562. hilog.error(0x0000, 'Heanup2', `❌ Failed to process widget control command: ${error}`);
  563. }
  564. }
  565. /**
  566. * 强制数据恢复(用于桌面卡片冷启动场景)
  567. */
  568. private async forceDataRestoration(unifiedService: UnifiedPlayerService): Promise<void> {
  569. try {
  570. hilog.info(0x0000, 'Heanup2', '🔄 开始强制数据恢复...');
  571. // 检查是否已经有数据恢复完成
  572. if (unifiedService.isDataRestorationCompleted()) {
  573. hilog.info(0x0000, 'Heanup2', '✅ 数据已恢复,无需强制恢复');
  574. return;
  575. }
  576. // 调用UnifiedPlayerService的强制数据恢复方法
  577. const restored = await unifiedService.forceDataRestoration();
  578. if (restored) {
  579. hilog.info(0x0000, 'Heanup2', '✅ 强制数据恢复成功');
  580. } else {
  581. hilog.warn(0x0000, 'Heanup2', '⚠️ 强制数据恢复失败,尝试等待');
  582. // 如果强制恢复失败,再等待一段时间
  583. await unifiedService.waitForDataRestoration(2000);
  584. }
  585. // 额外等待一小段时间,确保播放列表数据完全加载
  586. await new Promise<void>(resolve => setTimeout(resolve, 300));
  587. } catch (error) {
  588. hilog.error(0x0000, 'Heanup2', `❌ 强制数据恢复失败: ${error}`);
  589. }
  590. }
  591. /**
  592. * 智能等待服务就绪(增强版本)
  593. */
  594. private async waitForServiceReady(unifiedService: UnifiedPlayerService): Promise<boolean> {
  595. try {
  596. hilog.info(0x0000, 'Heanup2', '🔄 开始等待UnifiedPlayerService完全就绪');
  597. // 检查是否是刚启动的应用(数据还没恢复)
  598. const currentPlaylist = unifiedService.getPlaylist();
  599. const isJustStarted = currentPlaylist.length === 0;
  600. const isDataRestored = unifiedService.isDataRestorationCompleted();
  601. if (isJustStarted || !isDataRestored) {
  602. hilog.info(0x0000, 'Heanup2', `🔄 检测到冷启动状态 - 播放列表为空: ${isJustStarted}, 数据未恢复: ${!isDataRestored}`);
  603. // 对于冷启动,给予更长的等待时间,并强制检查数据恢复
  604. const isReady = await unifiedService.waitForAllServicesReady(10000, true);
  605. if (isReady) {
  606. hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService完全就绪(冷启动)');
  607. return true;
  608. }
  609. // 如果仍未就绪,尝试强制触发数据恢复
  610. hilog.warn(0x0000, 'Heanup2', '⚠️ 冷启动等待超时,尝试强制数据恢复');
  611. await this.forceDataRestoration(unifiedService);
  612. // 再次检查服务状态
  613. const retryReady = await unifiedService.waitForAllServicesReady(3000, false);
  614. if (retryReady) {
  615. hilog.info(0x0000, 'Heanup2', '✅ 强制恢复后服务就绪');
  616. return true;
  617. }
  618. } else {
  619. // 对于已经有数据的情况,使用正常的等待时间
  620. const isReady = await unifiedService.waitForAllServicesReady(5000, true);
  621. if (isReady) {
  622. hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService完全就绪');
  623. return true;
  624. }
  625. }
  626. // 如果主要服务就绪但数据未恢复,再做一次宽松检查
  627. hilog.info(0x0000, 'Heanup2', '⚠️ 主要检查超时,进行备用检查');
  628. const basicReady = await unifiedService.waitForAllServicesReady(2000, false);
  629. if (basicReady) {
  630. // 检查是否至少有播放数据
  631. const currentState = unifiedService.getCurrentState();
  632. const playlist = unifiedService.getPlaylist();
  633. if (playlist.length > 0 || currentState.currentIndex >= 0) {
  634. hilog.info(0x0000, 'Heanup2', `✅ 基础服务就绪,播放列表: ${playlist.length} 首歌曲`);
  635. return true;
  636. }
  637. }
  638. hilog.warn(0x0000, 'Heanup2', '⚠️ Service readiness check timeout, proceeding with limited functionality');
  639. return false;
  640. } catch (error) {
  641. hilog.error(0x0000, 'Heanup2', `❌ Error waiting for service ready: ${error}`);
  642. return false;
  643. }
  644. }
  645. /**
  646. * 异步初始化播放器服务,避免阻塞生命周期
  647. */
  648. private initializePlayerServiceAsync(): void {
  649. // 使用 setTimeout 将初始化操作移到下一个事件循环
  650. setTimeout(async () => {
  651. try {
  652. hilog.info(0x0000, 'Heanup2', '🔄 开始异步初始化 UnifiedPlayerService');
  653. await UnifiedPlayerService.getInstance().initialize(this.context);
  654. hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService 异步初始化成功');
  655. // 对于冷启动场景,立即尝试数据恢复
  656. const unifiedService = UnifiedPlayerService.getInstance();
  657. if (!unifiedService.isDataRestorationCompleted()) {
  658. hilog.info(0x0000, 'Heanup2', '🔄 冷启动检测到数据未恢复,开始预恢复');
  659. await unifiedService.forceDataRestoration();
  660. }
  661. // 延迟广播当前状态,确保卡片能接收到初始状态
  662. setTimeout(() => {
  663. this.broadcastCurrentPlayerState();
  664. }, 500); // 缩短延迟,让卡片更快收到状态
  665. } catch (error) {
  666. hilog.error(0x0000, 'Heanup2', `❌ UnifiedPlayerService 异步初始化失败: ${error}`);
  667. }
  668. }, 50); // 缩短延迟,让初始化更快开始
  669. }
  670. /**
  671. * 异步处理前台逻辑
  672. */
  673. private handleForegroundAsync(): void {
  674. try {
  675. hilog.info(0x0000, 'Heanup2', '🔄 处理前台逻辑');
  676. // 确保播放器服务可用
  677. const playerService = UnifiedPlayerService.getInstance();
  678. if (playerService) {
  679. // 广播当前状态给卡片
  680. this.broadcastCurrentPlayerState();
  681. }
  682. hilog.info(0x0000, 'Heanup2', '✅ 前台逻辑处理完成');
  683. } catch (error) {
  684. hilog.error(0x0000, 'Heanup2', `❌ 前台逻辑处理失败: ${error}`);
  685. }
  686. }
  687. /**
  688. * 异步处理后台逻辑
  689. */
  690. private handleBackgroundAsync(): void {
  691. try {
  692. hilog.info(0x0000, 'Heanup2', '🔄 处理后台逻辑');
  693. // 后台时可以执行一些清理或保存操作
  694. // 但要确保不会阻塞生命周期
  695. hilog.info(0x0000, 'Heanup2', '✅ 后台逻辑处理完成');
  696. } catch (error) {
  697. hilog.error(0x0000, 'Heanup2', `❌ 后台逻辑处理失败: ${error}`);
  698. }
  699. }
  700. /**
  701. * 异步处理Want参数,避免阻塞生命周期
  702. */
  703. private handleWantAsync(want: Want): void {
  704. setTimeout(async () => {
  705. try {
  706. this.loadDoWant(want);
  707. await this.handleParam(want);
  708. } catch (error) {
  709. hilog.error(0x0000, 'Heanup2', `❌ 处理Want参数失败: ${error}`);
  710. }
  711. }, 200);
  712. }
  713. /**
  714. * 异步执行卡片注册修复
  715. */
  716. private async fixWidgetRegistrationAsync(): Promise<void> {
  717. // 延迟3秒执行,确保应用完全启动
  718. setTimeout(async () => {
  719. try {
  720. const widgetFix = WidgetRegistrationFix.getInstance();
  721. await widgetFix.fixWidgetRegistration(this.context);
  722. } catch (error) {
  723. hilog.error(0x0000, 'Heanup2', `❌ 卡片注册修复失败: ${error}`);
  724. }
  725. }, 3000);
  726. }
  727. /**
  728. * 广播当前播放器状态给卡片
  729. */
  730. private broadcastCurrentPlayerState(): void {
  731. try {
  732. const unifiedService = UnifiedPlayerService.getInstance();
  733. const currentState = unifiedService.getCurrentState();
  734. const currentSong = unifiedService.getCurrentSong();
  735. const playlist = unifiedService.getPlaylist();
  736. const currentIndex = unifiedService.getCurrentIndex();
  737. if (currentSong) {
  738. // 构建播放器状态广播数据
  739. const broadcastData: BroadcastData = {
  740. playState: {
  741. isPlaying: currentState.isPlaying || false,
  742. isPaused: currentState.isPaused || true,
  743. isLoading: currentState.isLoading || false
  744. } as PlayStateBroadcast,
  745. currentSong: {
  746. id: currentSong.id || '',
  747. title: currentSong.name || '暂无播放',
  748. artist: currentSong.artist || '未知艺术家',
  749. album: currentSong.album || '未知专辑',
  750. coverImagePath: currentSong.pixelMapPath || '',
  751. duration: currentSong.duration ? Number(currentSong.duration) : 0
  752. } as SongBroadcast,
  753. progress: {
  754. currentPosition: currentState.currentPosition || 0,
  755. duration: currentState.duration || 0,
  756. percentage: this.calculatePercentage(currentState.currentPosition || 0, currentState.duration || 0),
  757. currentTimeText: this.formatTime(Math.floor((currentState.currentPosition || 0) / 1000)),
  758. totalTimeText: this.formatTime(Math.floor((currentState.duration || 0) / 1000))
  759. } as ProgressBroadcast,
  760. playlist: {
  761. hasNext: currentState.hasNext || false,
  762. hasPrevious: currentState.hasPrevious || false,
  763. currentIndex: currentIndex,
  764. totalCount: playlist.length
  765. } as PlaylistBroadcast
  766. };
  767. // 发送状态变化事件
  768. const publishInfo: PublishInfo = {
  769. data: JSON.stringify(broadcastData)
  770. };
  771. // 使用emitter发送事件
  772. const eventData: EventDataWrapper = {
  773. data: broadcastData
  774. };
  775. emitter.emit({ eventId: 1001 }, eventData); // 使用特定的事件ID
  776. hilog.info(0x0000, 'Heanup2', `📡 Broadcasted current player state: ${currentSong.name}, isPlaying=${currentState.isPlaying}`);
  777. } else {
  778. hilog.info(0x0000, 'Heanup2', '📡 No current song to broadcast');
  779. }
  780. } catch (error) {
  781. hilog.error(0x0000, 'Heanup2', `❌ Failed to broadcast current player state: ${error}`);
  782. }
  783. }
  784. /**
  785. * 计算播放进度百分比
  786. */
  787. private calculatePercentage(current: number, total: number): number {
  788. if (total <= 0) return 0;
  789. return Math.min(100, Math.max(0, (current / total) * 100));
  790. }
  791. /**
  792. * 格式化时间显示
  793. */
  794. private formatTime(seconds: number): string {
  795. const mins = Math.floor(seconds / 60);
  796. const secs = Math.floor(seconds % 60);
  797. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  798. }
  799. }