ForegroundService.ets 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { ServiceExtensionAbility, Want } from '@ohos.ability.ServiceExtensionAbility';
  2. import { NotificationManager } from '@ohos.notificationManager';
  3. import { BusinessError } from '@ohos.base';
  4. export default class ForegroundService extends ServiceExtensionAbility {
  5. onCreate(want: Want) {
  6. super.onCreate(want);
  7. // 初始化通知
  8. this.initNotification(want.parameters?.notificationTitle, want.parameters?.notificationContent);
  9. }
  10. initNotification(title: string, content: string) {
  11. const notificationRequest: NotificationManager.NotificationRequest = {
  12. id: 1,
  13. slotType: NotificationManager.SlotType.SERVICE_INFORMATION,
  14. content: {
  15. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  16. normal: {
  17. title: title || '服务运行中',
  18. text: content || '服务正在运行,更新中...',
  19. additionalText: ''
  20. }
  21. },
  22. wantAgent: {
  23. want: {
  24. bundleName: 'com.example.myapp',
  25. abilityName: 'EntryAbility'
  26. }
  27. }
  28. };
  29. NotificationManager.publish(notificationRequest, (err: BusinessError) => {
  30. if (err) {
  31. console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
  32. return;
  33. }
  34. console.info('Succeeded in publishing notification.');
  35. });
  36. }
  37. // 更新通知栏内容
  38. updateNotification(title: string, content: string) {
  39. const notificationRequest: NotificationManager.NotificationRequest = {
  40. id: 1,
  41. slotType: NotificationManager.SlotType.SERVICE_INFORMATION,
  42. content: {
  43. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  44. normal: {
  45. title: title,
  46. text: content,
  47. additionalText: ''
  48. }
  49. },
  50. wantAgent: {
  51. want: {
  52. bundleName: 'com.example.myapp',
  53. abilityName: 'EntryAbility'
  54. }
  55. }
  56. };
  57. NotificationManager.publish(notificationRequest, (err: BusinessError) => {
  58. if (err) {
  59. console.error(`Failed to update notification. Code is ${err.code}, message is ${err.message}`);
  60. return;
  61. }
  62. console.info('Succeeded in updating notification.');
  63. });
  64. }
  65. // 保活逻辑
  66. onForeground() {
  67. // 这里可以添加保活逻辑,例如定时更新通知
  68. setInterval(() => {
  69. // this.updateNotification('服务运行中', '服务正在运行,更新中...');
  70. }, 60 * 1000); // 每分钟更新一次
  71. }
  72. // 服务销毁时的清理逻辑
  73. onDestroy() {
  74. super.onDestroy();
  75. // 取消通知
  76. NotificationManager.cancel(1, (err: BusinessError) => {
  77. if (err) {
  78. console.error(`Failed to cancel notification. Code is ${err.code}, message is ${err.message}`);
  79. return;
  80. }
  81. console.info('Succeeded in canceling notification.');
  82. });
  83. }
  84. }