EntryAbility.ets 36 KB

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