PlayerControlService.ets 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import commonEventManager from '@ohos.commonEventManager';
  2. import Want from '@ohos.app.ability.Want';
  3. import common from '@ohos.app.ability.common';
  4. import { hilog } from '@kit.PerformanceAnalysisKit';
  5. import { WidgetData, WidgetCommand, EventData, RequestData, WidgetControlParams } from './WidgetTypes';
  6. import {
  7. WIDGET_CONTROL_EVENT,
  8. WIDGET_REQUEST_STATE_EVENT,
  9. PLAYER_STATE_CHANGED_EVENT,
  10. PLAYER_SONG_CHANGED_EVENT,
  11. PLAYER_PROGRESS_CHANGED_EVENT,
  12. APP_BUNDLE_NAME,
  13. APP_ABILITY_NAME
  14. } from './WidgetEventConstants';
  15. const TAG = 'PlayerControlService';
  16. /**
  17. * 播放器控制服务
  18. * 负责与主应用的播放器进行通信和状态同步
  19. */
  20. export class PlayerControlService {
  21. private stateListeners: Array<(data: WidgetData) => void> = [];
  22. private isListenerRegistered: boolean = false;
  23. constructor() {
  24. this.initializeEventListener();
  25. }
  26. /**
  27. * 初始化事件监听器
  28. */
  29. private async initializeEventListener(): Promise<void> {
  30. if (this.isListenerRegistered) {
  31. return;
  32. }
  33. try {
  34. // 监听播放状态变化事件
  35. const subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  36. events: [
  37. PLAYER_STATE_CHANGED_EVENT,
  38. PLAYER_SONG_CHANGED_EVENT,
  39. PLAYER_PROGRESS_CHANGED_EVENT
  40. ]
  41. };
  42. const subscriber = await commonEventManager.createSubscriber(subscribeInfo);
  43. await commonEventManager.subscribe(subscriber, (err, data: commonEventManager.CommonEventData) => {
  44. if (!err) {
  45. this.handlePlayerStateChange(data);
  46. }
  47. });
  48. this.isListenerRegistered = true;
  49. hilog.info(0x0000, TAG, 'Event listener initialized successfully');
  50. } catch (error) {
  51. hilog.error(0x0000, TAG, `Failed to initialize event listener: ${error}`);
  52. }
  53. }
  54. /**
  55. * 发送控制命令到主应用
  56. */
  57. async sendControlCommand(command: WidgetCommand, params?: WidgetControlParams): Promise<boolean> {
  58. try {
  59. const defaultParams: WidgetControlParams = {};
  60. const eventData: EventData = {
  61. command: command,
  62. params: params || defaultParams,
  63. timestamp: Date.now(),
  64. source: 'widget'
  65. };
  66. // 发送CommonEvent到主应用
  67. const publishInfo: commonEventManager.CommonEventPublishData = {
  68. data: JSON.stringify(eventData)
  69. };
  70. await commonEventManager.publish(WIDGET_CONTROL_EVENT, publishInfo, (err) => {
  71. if (err) {
  72. hilog.error(0x0000, TAG, `Failed to publish event: ${err}`);
  73. }
  74. });
  75. hilog.info(0x0000, TAG, `Control command sent: ${command}`);
  76. return true;
  77. } catch (error) {
  78. hilog.error(0x0000, TAG, `Failed to send control command: ${error}`);
  79. return false;
  80. }
  81. }
  82. /**
  83. * 获取当前播放状态
  84. */
  85. async getCurrentPlayState(): Promise<WidgetData> {
  86. try {
  87. // 请求当前状态
  88. const requestData: RequestData = { timestamp: Date.now() };
  89. const requestInfo: commonEventManager.CommonEventPublishData = {
  90. data: JSON.stringify(requestData)
  91. };
  92. await commonEventManager.publish(WIDGET_REQUEST_STATE_EVENT, requestInfo, (err) => {
  93. if (err) {
  94. hilog.error(0x0000, TAG, `Failed to publish request state event: ${err}`);
  95. }
  96. });
  97. // 返回默认状态,实际状态会通过事件监听器更新
  98. return this.getDefaultWidgetData();
  99. } catch (error) {
  100. hilog.error(0x0000, TAG, `Failed to get current play state: ${error}`);
  101. return this.getDefaultWidgetData();
  102. }
  103. }
  104. /**
  105. * 注册状态变化监听器
  106. */
  107. registerStateListener(callback: (data: WidgetData) => void): void {
  108. this.stateListeners.push(callback);
  109. hilog.info(0x0000, TAG, 'State listener registered');
  110. }
  111. /**
  112. * 启动主应用
  113. */
  114. async launchMainApp(page?: string): Promise<boolean> {
  115. try {
  116. const want: Want = {
  117. bundleName: APP_BUNDLE_NAME,
  118. abilityName: APP_ABILITY_NAME,
  119. parameters: {
  120. page: page || 'main',
  121. source: 'widget', // 标识来源是卡片
  122. timestamp: Date.now().toString()
  123. }
  124. };
  125. const context = getContext() as common.UIAbilityContext;
  126. await context.startAbility(want);
  127. hilog.info(0x0000, TAG, `Main app launched with page: ${page}`);
  128. return true;
  129. } catch (error) {
  130. hilog.error(0x0000, TAG, `Failed to launch main app: ${error}`);
  131. // 如果启动失败,尝试启动到默认页面
  132. try {
  133. const fallbackWant: Want = {
  134. bundleName: APP_BUNDLE_NAME,
  135. abilityName: APP_ABILITY_NAME
  136. };
  137. const context = getContext() as common.UIAbilityContext;
  138. await context.startAbility(fallbackWant);
  139. hilog.info(0x0000, TAG, 'Main app launched with fallback method');
  140. return true;
  141. } catch (fallbackError) {
  142. hilog.error(0x0000, TAG, `Fallback launch also failed: ${fallbackError}`);
  143. return false;
  144. }
  145. }
  146. }
  147. /**
  148. * 处理播放器状态变化
  149. */
  150. private handlePlayerStateChange(eventData: commonEventManager.CommonEventData): void {
  151. try {
  152. const data = JSON.parse(eventData.data || '{}') as Object;
  153. const widgetData = this.convertToWidgetData(data);
  154. // 通知所有监听器
  155. this.stateListeners.forEach((listener: (data: WidgetData) => void) => {
  156. try {
  157. listener(widgetData);
  158. } catch (error) {
  159. hilog.error(0x0000, TAG, `Error in state listener: ${error}`);
  160. }
  161. });
  162. hilog.info(0x0000, TAG, 'Player state change handled');
  163. } catch (error) {
  164. hilog.error(0x0000, TAG, `Failed to handle player state change: ${error}`);
  165. }
  166. }
  167. /**
  168. * 转换播放器数据为卡片数据格式
  169. */
  170. private convertToWidgetData(playerData: Object): WidgetData {
  171. // 返回默认的卡片数据,避免索引访问
  172. return this.getDefaultWidgetData();
  173. }
  174. /**
  175. * 获取默认卡片数据
  176. */
  177. private getDefaultWidgetData(): WidgetData {
  178. return {
  179. playState: {
  180. isPlaying: false,
  181. isPaused: true,
  182. isLoading: false
  183. },
  184. currentSong: {
  185. id: '',
  186. title: '暂无播放',
  187. artist: '未知艺术家',
  188. album: '未知专辑',
  189. coverImagePath: '',
  190. duration: 0
  191. },
  192. progress: {
  193. currentPosition: 0,
  194. duration: 0,
  195. percentage: 0,
  196. currentTimeText: '00:00',
  197. totalTimeText: '00:00'
  198. },
  199. playlist: {
  200. hasNext: false,
  201. hasPrevious: false,
  202. currentIndex: 0,
  203. totalCount: 0
  204. },
  205. config: {
  206. size: 'medium',
  207. theme: 'auto',
  208. showProgress: true,
  209. showCover: true
  210. }
  211. };
  212. }
  213. /**
  214. * 计算播放进度百分比
  215. */
  216. private calculatePercentage(current: number, total: number): number {
  217. if (total <= 0) return 0;
  218. return Math.min(100, Math.max(0, (current / total) * 100));
  219. }
  220. /**
  221. * 格式化时间显示
  222. */
  223. private formatTime(seconds: number): string {
  224. const mins = Math.floor(seconds / 60);
  225. const secs = Math.floor(seconds % 60);
  226. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  227. }
  228. }