EntryAbility.ets 37 KB

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