@hxa-rn/react-native-background-actions 0.0.0-stage → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +178 -3
- package/harmony/background_actions/LICENSE +22 -0
- package/harmony/background_actions/NOTICE +33 -0
- package/harmony/background_actions/OAT.xml +38 -0
- package/harmony/background_actions/build-profile.json5 +16 -0
- package/harmony/background_actions/hvigorfile.ts +2 -0
- package/harmony/background_actions/index.ets +1 -0
- package/harmony/background_actions/oh-package.json5 +14 -0
- package/harmony/background_actions/src/main/cpp/BackgroundActionsPackage.h +26 -0
- package/harmony/background_actions/src/main/cpp/BackgroundActionsTimerModule.cpp +54 -0
- package/harmony/background_actions/src/main/cpp/BackgroundActionsTimerModule.h +35 -0
- package/harmony/background_actions/src/main/cpp/CMakeLists.txt +3 -0
- package/harmony/background_actions/src/main/cpp/bridge/CMakeLists.txt +8 -0
- package/harmony/background_actions/src/main/cpp/generated/RNBackgroundActions.cpp +30 -0
- package/harmony/background_actions/src/main/cpp/generated/RNBackgroundActions.h +21 -0
- package/harmony/background_actions/src/main/cpp/generated/RNOHGeneratedPackage.h +76 -0
- package/harmony/background_actions/src/main/ets/BackgroundActionsModule.ets +425 -0
- package/harmony/background_actions/src/main/ets/BackgroundActionsTurboModulesFactory.ets +9 -0
- package/harmony/background_actions/src/main/ets/generated/components/ts.ts +5 -0
- package/harmony/background_actions/src/main/ets/generated/index.ets +8 -0
- package/harmony/background_actions/src/main/ets/generated/ts.ts +9 -0
- package/harmony/background_actions/src/main/ets/generated/turboModules/RNBackgroundActions.ts +65 -0
- package/harmony/background_actions/src/main/ets/generated/turboModules/ts.ts +8 -0
- package/harmony/background_actions/src/main/module.json5 +13 -0
- package/harmony/background_actions/src/main/resources/base/element/string.json +8 -0
- package/harmony/background_actions/src/main/resources/en_US/element/string.json +8 -0
- package/harmony/background_actions/src/main/resources/zh_CN/element/string.json +8 -0
- package/harmony/background_actions.har +0 -0
- package/package.json +84 -6
- package/src/BackgroundTimers.ts +72 -0
- package/src/RNBackgroundActionsModule.ts +78 -0
- package/src/index.ts +131 -0
- package/src/specs/v1/.gitkeep +1 -0
- package/src/specs/v1/NativeRNBackgroundActionsSpec.ts +27 -0
- package/src/specs/v2/.gitkeep +1 -0
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
import { UITurboModule, UITurboModuleContext } from '@rnoh/react-native-openharmony/ts';
|
|
2
|
+
import { TM } from './generated/ts';
|
|
3
|
+
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
|
|
4
|
+
import { notificationManager } from '@kit.NotificationKit';
|
|
5
|
+
import { wantAgent, Want, WantAgent } from '@kit.AbilityKit';
|
|
6
|
+
import { image } from '@kit.ImageKit';
|
|
7
|
+
import { deviceInfo, BusinessError } from '@kit.BasicServicesKit';
|
|
8
|
+
|
|
9
|
+
interface ExpirationPayload { generation: number; reason: string; }
|
|
10
|
+
interface CleanupFailure {
|
|
11
|
+
operation: string;
|
|
12
|
+
code: string;
|
|
13
|
+
message: string;
|
|
14
|
+
}
|
|
15
|
+
interface BackgroundActionFailure extends Error {
|
|
16
|
+
cleanupErrors?: CleanupFailure[];
|
|
17
|
+
}
|
|
18
|
+
class BackgroundActionError extends Error {
|
|
19
|
+
code: string;
|
|
20
|
+
constructor(code: string, message: string) { super(`${code}: ${message}`); this.code = code; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class BackgroundActionsModule extends UITurboModule implements TM.RNBackgroundActions.Spec {
|
|
24
|
+
private running: boolean = false;
|
|
25
|
+
private requestId: number = -1;
|
|
26
|
+
private continuousTaskId: number = -1;
|
|
27
|
+
private continuous: boolean = false;
|
|
28
|
+
private notificationId: number = 92901;
|
|
29
|
+
private published: boolean = false;
|
|
30
|
+
private systemNotification: boolean = false;
|
|
31
|
+
private ended: boolean = false;
|
|
32
|
+
private actualDelayTime: number = 0;
|
|
33
|
+
private mode: string = 'idle';
|
|
34
|
+
private generation: number = 0;
|
|
35
|
+
private listenerCount: number = 0;
|
|
36
|
+
private stopping: boolean = false;
|
|
37
|
+
private observing: boolean = false;
|
|
38
|
+
private lastErrorCode: string = '';
|
|
39
|
+
private lastErrorMessage: string = '';
|
|
40
|
+
private queue: Promise<void> = Promise.resolve();
|
|
41
|
+
private cancelled = (info: backgroundTaskManager.ContinuousTaskCancelInfo): void => {
|
|
42
|
+
if (!this.continuous || info.id !== this.continuousTaskId) { return; }
|
|
43
|
+
this.continuous = false;
|
|
44
|
+
this.continuousTaskId = -1;
|
|
45
|
+
if (this.systemNotification) { this.published = false; }
|
|
46
|
+
if (!this.stopping) { this.expire(this.generation, `continuousTaskCancel:${info.reason}`); }
|
|
47
|
+
};
|
|
48
|
+
constructor(ctx: UITurboModuleContext) { super(ctx); }
|
|
49
|
+
private serialize(operation: () => Promise<void>): Promise<void> {
|
|
50
|
+
const result = this.queue.then(operation);
|
|
51
|
+
this.queue = result.catch((error: BusinessError) => { this.record(error); });
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
private record(error: BusinessError): void {
|
|
55
|
+
this.lastErrorCode = String(error.code ?? 'E_NATIVE');
|
|
56
|
+
this.lastErrorMessage = error.message;
|
|
57
|
+
}
|
|
58
|
+
private fail(code: string, message: string): void { throw new BackgroundActionError(code, message); }
|
|
59
|
+
private cleanupFailure(operation: string, error: Error): CleanupFailure {
|
|
60
|
+
return {
|
|
61
|
+
operation: operation,
|
|
62
|
+
code: String((error as BusinessError).code ?? 'E_NATIVE'),
|
|
63
|
+
message: error.message
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
private withCleanupErrors(primaryError: Error, cleanupErrors: CleanupFailure[]): Error {
|
|
67
|
+
const failure = primaryError as BackgroundActionFailure;
|
|
68
|
+
failure.cleanupErrors = (failure.cleanupErrors ?? []).concat(cleanupErrors);
|
|
69
|
+
return primaryError;
|
|
70
|
+
}
|
|
71
|
+
private requireCapability(capability: string): void {
|
|
72
|
+
if (!canIUse(capability)) {
|
|
73
|
+
this.fail('E_UNSUPPORTED_CAPABILITY', `Device does not support ${capability}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
addListener(eventName: string): void {
|
|
77
|
+
if (eventName !== 'expiration') { this.fail('E_EVENT', `Unsupported event: ${eventName}`); }
|
|
78
|
+
this.listenerCount++;
|
|
79
|
+
}
|
|
80
|
+
removeListeners(count: number): void {
|
|
81
|
+
if (!Number.isFinite(count) || count < 0 || Math.floor(count) !== count) {
|
|
82
|
+
this.fail('E_LISTENER_COUNT', 'count must be a nonnegative integer');
|
|
83
|
+
}
|
|
84
|
+
this.listenerCount = Math.max(0, this.listenerCount - count);
|
|
85
|
+
}
|
|
86
|
+
scheduleTimer(id: number, delay: number, repeats: boolean): void {
|
|
87
|
+
if (!Number.isFinite(id) || id >= 0 || Math.floor(id) !== id ||
|
|
88
|
+
!Number.isFinite(delay) || delay < 0 || delay > 2147483647) {
|
|
89
|
+
this.fail('E_INVALID_TIMER', 'Invalid timer id or delay');
|
|
90
|
+
}
|
|
91
|
+
this.ctx.rnInstance.postMessageToCpp('BACKGROUND_ACTIONS_TIMER', { id: id, delay: delay, repeats: repeats });
|
|
92
|
+
}
|
|
93
|
+
cancelTimer(id: number): void {
|
|
94
|
+
this.ctx.rnInstance.postMessageToCpp('BACKGROUND_ACTIONS_CLEAR_TIMER', { id: id });
|
|
95
|
+
}
|
|
96
|
+
isRunning(): boolean { return this.running; }
|
|
97
|
+
async getStatus(): Promise<TM.RNBackgroundActions.TaskStatus> {
|
|
98
|
+
return { running: this.running,
|
|
99
|
+
mode: this.mode,
|
|
100
|
+
requestId: this.requestId,
|
|
101
|
+
notificationId: this.notificationId,
|
|
102
|
+
actualDelayTime: this.actualDelayTime,
|
|
103
|
+
cancelEventsSupported: deviceInfo.sdkApiVersion >= 15,
|
|
104
|
+
lastErrorCode: this.lastErrorCode,
|
|
105
|
+
lastErrorMessage: this.lastErrorMessage };
|
|
106
|
+
}
|
|
107
|
+
async requestNotifications(): Promise<boolean> {
|
|
108
|
+
this.requireCapability('SystemCapability.Notification.Notification');
|
|
109
|
+
if (!await notificationManager.isNotificationEnabled()) {
|
|
110
|
+
await notificationManager.requestEnableNotification(this.ctx.uiAbilityContext);
|
|
111
|
+
}
|
|
112
|
+
return notificationManager.isNotificationEnabled();
|
|
113
|
+
}
|
|
114
|
+
private modes(options: TM.RNBackgroundActions.NativeOptions): string[] {
|
|
115
|
+
const modes: string[] = [];
|
|
116
|
+
let short: boolean = false;
|
|
117
|
+
for (const type of options.foregroundServiceType ?? []) {
|
|
118
|
+
let mode: string = '';
|
|
119
|
+
switch (type) {
|
|
120
|
+
case 'shortService':
|
|
121
|
+
short = true;
|
|
122
|
+
break;
|
|
123
|
+
case 'dataSync':
|
|
124
|
+
mode = 'dataTransfer';
|
|
125
|
+
break;
|
|
126
|
+
case 'mediaPlayback':
|
|
127
|
+
mode = 'audioPlayback';
|
|
128
|
+
break;
|
|
129
|
+
case 'phoneCall':
|
|
130
|
+
mode = 'voip';
|
|
131
|
+
break;
|
|
132
|
+
case 'location':
|
|
133
|
+
mode = 'location';
|
|
134
|
+
break;
|
|
135
|
+
case 'microphone':
|
|
136
|
+
mode = 'audioRecording';
|
|
137
|
+
break;
|
|
138
|
+
case 'connectedDevice':
|
|
139
|
+
this.explicitModes(options, ['bluetoothInteraction', 'multiDeviceConnection'], modes);
|
|
140
|
+
break;
|
|
141
|
+
case 'mediaProjection':
|
|
142
|
+
this.explicitModes(options, ['audioRecording', 'audioPlayback', 'multiDeviceConnection'], modes);
|
|
143
|
+
break;
|
|
144
|
+
case 'camera':
|
|
145
|
+
case 'health':
|
|
146
|
+
case 'remoteMessaging':
|
|
147
|
+
case 'systemExempted':
|
|
148
|
+
case 'specialUse':
|
|
149
|
+
this.fail('E_UNSUPPORTED_TYPE', `${type} has no generic public background mode on this API13 baseline`);
|
|
150
|
+
break;
|
|
151
|
+
default:
|
|
152
|
+
this.fail('E_UNSUPPORTED_TYPE', `Unknown foregroundServiceType: ${type}`);
|
|
153
|
+
}
|
|
154
|
+
if (mode && !modes.includes(mode)) { modes.push(mode); }
|
|
155
|
+
}
|
|
156
|
+
if (short && modes.length > 0) { this.fail('E_MIXED_MODE', 'shortService cannot be mixed with continuous modes'); }
|
|
157
|
+
return modes;
|
|
158
|
+
}
|
|
159
|
+
private explicitModes(options: TM.RNBackgroundActions.NativeOptions, allowed: string[], modes: string[]): void {
|
|
160
|
+
const selected = options.harmonyBackgroundModes ?? [];
|
|
161
|
+
if (selected.length === 0) {
|
|
162
|
+
this.fail('E_AMBIGUOUS_TYPE', 'Specify harmonyBackgroundModes for connectedDevice/mediaProjection business');
|
|
163
|
+
}
|
|
164
|
+
for (const mode of selected) {
|
|
165
|
+
if (!allowed.includes(mode)) { this.fail('E_INVALID_MODE', `Invalid business mode ${mode} for this type`); }
|
|
166
|
+
if (!modes.includes(mode)) { modes.push(mode); }
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
private validate(options: TM.RNBackgroundActions.NativeOptions): void {
|
|
170
|
+
if (!options || typeof options.taskName !== 'string' || !options.taskName.trim() ||
|
|
171
|
+
typeof options.taskTitle !== 'string' || typeof options.taskDesc !== 'string') {
|
|
172
|
+
this.fail('E_INVALID_OPTIONS', 'taskName/title/description must be strings');
|
|
173
|
+
}
|
|
174
|
+
if (options.generation !== undefined && (!Number.isFinite(options.generation) ||
|
|
175
|
+
options.generation < 1 || Math.floor(options.generation) !== options.generation)) {
|
|
176
|
+
this.fail('E_INVALID_OPTIONS', 'generation must be a positive integer');
|
|
177
|
+
}
|
|
178
|
+
const icon = options.taskIcon;
|
|
179
|
+
if (!icon || !icon.name || !['mipmap', 'drawable', 'media'].includes(icon.type)) {
|
|
180
|
+
this.fail('E_INVALID_ICON', 'taskIcon requires a media resource name and mipmap/drawable/media type');
|
|
181
|
+
}
|
|
182
|
+
if (icon.package && icon.package !== this.ctx.uiAbilityContext.abilityInfo.bundleName) {
|
|
183
|
+
this.fail('E_UNSUPPORTED_ICON_PACKAGE', 'Cross-application Android resource packages are not HarmonyOS media resources');
|
|
184
|
+
}
|
|
185
|
+
if (options.linkingURI && !new RegExp('^[a-zA-Z][a-zA-Z0-9+.-]*:\\S+$').test(options.linkingURI)) {
|
|
186
|
+
this.fail('E_INVALID_URI', 'linkingURI must be absolute');
|
|
187
|
+
}
|
|
188
|
+
const progress = options.progressBar;
|
|
189
|
+
if (progress) {
|
|
190
|
+
if (progress.indeterminate) { this.fail('E_UNSUPPORTED_PROGRESS', 'downloadTemplate requires a numeric percentage; indeterminate style unsupported'); }
|
|
191
|
+
if (!Number.isFinite(progress.max) || !Number.isFinite(progress.value) || Math.floor(progress.max) <= 0 ||
|
|
192
|
+
Math.floor(progress.value) < 0 || Math.floor(progress.value) > Math.floor(progress.max)) {
|
|
193
|
+
this.fail('E_INVALID_PROGRESS', 'Require max > 0 and 0 <= value <= max');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
private async intent(options: TM.RNBackgroundActions.NativeOptions): Promise<WantAgent> {
|
|
198
|
+
const context = this.ctx.uiAbilityContext;
|
|
199
|
+
const want: Want = { bundleName: context.abilityInfo.bundleName,
|
|
200
|
+
abilityName: context.abilityInfo.name,
|
|
201
|
+
uri: options.linkingURI,
|
|
202
|
+
parameters: { 'backgroundActionsURI': options.linkingURI ?? '',
|
|
203
|
+
'backgroundActionsTaskName': options.taskName } };
|
|
204
|
+
const info: wantAgent.WantAgentInfo = { wants: [want],
|
|
205
|
+
requestCode: options.generation ?? this.generation,
|
|
206
|
+
actionType: wantAgent.OperationType.START_ABILITY,
|
|
207
|
+
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] };
|
|
208
|
+
return wantAgent.getWantAgent(info);
|
|
209
|
+
}
|
|
210
|
+
private async icon(options: TM.RNBackgroundActions.NativeOptions): Promise<image.PixelMap> {
|
|
211
|
+
this.requireCapability('SystemCapability.Multimedia.Image.ImageSource');
|
|
212
|
+
this.requireCapability('SystemCapability.Multimedia.Image.Core');
|
|
213
|
+
const bytes = await this.ctx.uiAbilityContext.resourceManager.getMediaByName(options.taskIcon.name);
|
|
214
|
+
const source = image.createImageSource(bytes.buffer);
|
|
215
|
+
let failure: Error | undefined = undefined;
|
|
216
|
+
let pixelMap: image.PixelMap | undefined = undefined;
|
|
217
|
+
try {
|
|
218
|
+
const decoding: image.DecodingOptions = { desiredSize: { width: 64, height: 64 } };
|
|
219
|
+
pixelMap = await source.createPixelMap(decoding);
|
|
220
|
+
return pixelMap;
|
|
221
|
+
} catch (error) {
|
|
222
|
+
failure = error as Error;
|
|
223
|
+
throw failure;
|
|
224
|
+
} finally {
|
|
225
|
+
try {
|
|
226
|
+
await source.release();
|
|
227
|
+
} catch (error) {
|
|
228
|
+
const cleanupErrors: CleanupFailure[] = [this.cleanupFailure('icon:ImageSource.release', error as Error)];
|
|
229
|
+
// A decoded result cannot reach the caller if ImageSource cleanup fails.
|
|
230
|
+
if (pixelMap) {
|
|
231
|
+
try {
|
|
232
|
+
await pixelMap.release();
|
|
233
|
+
} catch (pixelError) {
|
|
234
|
+
cleanupErrors.push(this.cleanupFailure('icon:PixelMap.release', pixelError as Error));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
throw this.withCleanupErrors(failure ?? error as Error, cleanupErrors);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
private async publish(options: TM.RNBackgroundActions.NativeOptions, icon: image.PixelMap,
|
|
242
|
+
agent: WantAgent, transfer: boolean): Promise<void> {
|
|
243
|
+
this.requireCapability('SystemCapability.Notification.Notification');
|
|
244
|
+
const request: notificationManager.NotificationRequest = {
|
|
245
|
+
id: this.notificationId,
|
|
246
|
+
isAlertOnce: true,
|
|
247
|
+
tapDismissed: false,
|
|
248
|
+
smallIcon: icon,
|
|
249
|
+
largeIcon: icon,
|
|
250
|
+
wantAgent: agent,
|
|
251
|
+
notificationSlotType: notificationManager.SlotType.SERVICE_INFORMATION,
|
|
252
|
+
content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
|
|
253
|
+
normal: { title: options.taskTitle, text: options.taskDesc } }
|
|
254
|
+
};
|
|
255
|
+
if (transfer) {
|
|
256
|
+
request.notificationSlotType = notificationManager.SlotType.LIVE_VIEW;
|
|
257
|
+
request.content = {
|
|
258
|
+
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW,
|
|
259
|
+
systemLiveView: { typeCode: 8, title: options.taskTitle, text: options.taskDesc } };
|
|
260
|
+
}
|
|
261
|
+
if (transfer || options.progressBar) {
|
|
262
|
+
if (!await notificationManager.isSupportTemplate('downloadTemplate')) {
|
|
263
|
+
this.fail('E_UNSUPPORTED_PROGRESS', 'Device does not support downloadTemplate');
|
|
264
|
+
}
|
|
265
|
+
const data: Record<string, Object> = { 'title': options.taskTitle,
|
|
266
|
+
'fileName': options.taskDesc,
|
|
267
|
+
'progressValue': options.progressBar ?
|
|
268
|
+
Math.floor(Math.floor(options.progressBar.value) * 100 / Math.floor(options.progressBar.max)) : 0 };
|
|
269
|
+
request.template = { name: 'downloadTemplate', data: data };
|
|
270
|
+
}
|
|
271
|
+
await notificationManager.publish(request);
|
|
272
|
+
this.published = true;
|
|
273
|
+
}
|
|
274
|
+
start(options: TM.RNBackgroundActions.NativeOptions): Promise<void> {
|
|
275
|
+
return this.serialize(async () => {
|
|
276
|
+
this.validate(options);
|
|
277
|
+
const modes = this.modes(options);
|
|
278
|
+
this.requireCapability(modes.length === 0 ?
|
|
279
|
+
'SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask' :
|
|
280
|
+
'SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask');
|
|
281
|
+
const icon = await this.icon(options);
|
|
282
|
+
let failure: Error | undefined = undefined;
|
|
283
|
+
try {
|
|
284
|
+
const agent = await this.intent(options);
|
|
285
|
+
if (!await this.requestNotifications()) { this.fail('E_NOTIFICATION_DENIED', 'Notifications disabled by user'); }
|
|
286
|
+
await this.release();
|
|
287
|
+
const generation = options.generation ?? this.generation + 1;
|
|
288
|
+
this.generation = generation;
|
|
289
|
+
this.ended = false;
|
|
290
|
+
this.systemNotification = modes.includes('dataTransfer');
|
|
291
|
+
this.lastErrorCode = '';
|
|
292
|
+
this.lastErrorMessage = '';
|
|
293
|
+
this.notificationId = 92901;
|
|
294
|
+
this.actualDelayTime = 0;
|
|
295
|
+
this.mode = modes.length > 0 ? modes.join(',') : 'shortService';
|
|
296
|
+
try {
|
|
297
|
+
if (modes.length === 0) {
|
|
298
|
+
const result = backgroundTaskManager.requestSuspendDelay(options.taskTitle || options.taskName,
|
|
299
|
+
() => { this.expire(generation, 'shortTaskExpiration'); });
|
|
300
|
+
this.requestId = result.requestId;
|
|
301
|
+
this.actualDelayTime = result.actualDelayTime;
|
|
302
|
+
} else {
|
|
303
|
+
if (deviceInfo.sdkApiVersion >= 15) {
|
|
304
|
+
backgroundTaskManager.on('continuousTaskCancel', this.cancelled);
|
|
305
|
+
this.observing = true;
|
|
306
|
+
}
|
|
307
|
+
const result = await backgroundTaskManager.startBackgroundRunning(this.ctx.uiAbilityContext, modes, agent);
|
|
308
|
+
this.continuous = true;
|
|
309
|
+
this.continuousTaskId = result.continuousTaskId ?? -1;
|
|
310
|
+
if (modes.includes('dataTransfer')) { this.notificationId = result.notificationId; }
|
|
311
|
+
}
|
|
312
|
+
await this.publish(options, icon, agent, modes.includes('dataTransfer'));
|
|
313
|
+
if (this.ended) { this.fail('E_TASK_ENDED', 'System ended the task before startup completed'); }
|
|
314
|
+
this.running = true;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
this.record(error as BusinessError);
|
|
317
|
+
await this.release(error as Error);
|
|
318
|
+
throw error as Error;
|
|
319
|
+
}
|
|
320
|
+
} catch (error) {
|
|
321
|
+
failure = error as Error;
|
|
322
|
+
throw failure;
|
|
323
|
+
} finally {
|
|
324
|
+
try {
|
|
325
|
+
await icon.release();
|
|
326
|
+
} catch (error) {
|
|
327
|
+
throw this.withCleanupErrors(failure ?? error as Error,
|
|
328
|
+
[this.cleanupFailure('start:PixelMap.release', error as Error)]);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
updateNotification(options: TM.RNBackgroundActions.NativeOptions): Promise<void> {
|
|
334
|
+
return this.serialize(async () => {
|
|
335
|
+
if (!this.running) { this.fail('E_NOT_RUNNING', 'No background action is running'); }
|
|
336
|
+
if (options.generation !== undefined && options.generation !== this.generation) { this.fail('E_STALE_TASK', 'Notification belongs to an old task'); }
|
|
337
|
+
this.validate(options);
|
|
338
|
+
const icon = await this.icon(options);
|
|
339
|
+
let failure: Error | undefined = undefined;
|
|
340
|
+
try {
|
|
341
|
+
const agent = await this.intent(options);
|
|
342
|
+
if (!this.running) { this.fail('E_TASK_ENDED', 'Task ended while preparing notification'); }
|
|
343
|
+
await this.publish(options, icon, agent, this.mode.includes('dataTransfer'));
|
|
344
|
+
if (!this.running) { this.fail('E_TASK_ENDED', 'Task ended during notification publication'); }
|
|
345
|
+
} catch (error) {
|
|
346
|
+
failure = error as Error;
|
|
347
|
+
throw failure;
|
|
348
|
+
} finally {
|
|
349
|
+
try {
|
|
350
|
+
await icon.release();
|
|
351
|
+
} catch (error) {
|
|
352
|
+
throw this.withCleanupErrors(failure ?? error as Error,
|
|
353
|
+
[this.cleanupFailure('updateNotification:PixelMap.release', error as Error)]);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
stop(): Promise<void> { return this.serialize(async () => { await this.release(); }); }
|
|
359
|
+
private async release(primaryError: Error | undefined = undefined): Promise<void> {
|
|
360
|
+
const cleanupErrors: CleanupFailure[] = [];
|
|
361
|
+
let failure: Error | undefined = undefined;
|
|
362
|
+
if (this.requestId >= 0) {
|
|
363
|
+
try {
|
|
364
|
+
backgroundTaskManager.cancelSuspendDelay(this.requestId);
|
|
365
|
+
this.requestId = -1;
|
|
366
|
+
} catch (error) {
|
|
367
|
+
failure = failure ?? error as Error;
|
|
368
|
+
cleanupErrors.push(this.cleanupFailure('release:cancelSuspendDelay', error as Error));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (this.continuous) {
|
|
372
|
+
this.stopping = true;
|
|
373
|
+
try {
|
|
374
|
+
await backgroundTaskManager.stopBackgroundRunning(this.ctx.uiAbilityContext);
|
|
375
|
+
this.continuous = false;
|
|
376
|
+
this.continuousTaskId = -1;
|
|
377
|
+
} catch (error) {
|
|
378
|
+
failure = failure ?? error as Error;
|
|
379
|
+
cleanupErrors.push(this.cleanupFailure('release:stopBackgroundRunning', error as Error));
|
|
380
|
+
} finally {
|
|
381
|
+
this.stopping = false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
this.running = !this.ended && (this.requestId >= 0 || this.continuous);
|
|
385
|
+
if (!this.continuous && this.systemNotification) { this.published = false; }
|
|
386
|
+
if (this.observing && !this.continuous) {
|
|
387
|
+
try {
|
|
388
|
+
backgroundTaskManager.off('continuousTaskCancel', this.cancelled);
|
|
389
|
+
this.observing = false;
|
|
390
|
+
} catch (error) {
|
|
391
|
+
failure = failure ?? error as Error;
|
|
392
|
+
cleanupErrors.push(this.cleanupFailure('release:continuousTaskCancel.off', error as Error));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (this.published) {
|
|
396
|
+
try {
|
|
397
|
+
await notificationManager.cancel(this.notificationId);
|
|
398
|
+
this.published = false;
|
|
399
|
+
} catch (error) {
|
|
400
|
+
failure = failure ?? error as Error;
|
|
401
|
+
cleanupErrors.push(this.cleanupFailure('release:notification.cancel', error as Error));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (!this.running) { this.mode = 'idle'; }
|
|
405
|
+
if (failure) {
|
|
406
|
+
throw this.withCleanupErrors(primaryError ?? failure, cleanupErrors);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
private expire(generation: number, reason: string): void {
|
|
410
|
+
if (generation !== this.generation || this.ended) { return; }
|
|
411
|
+
this.running = false;
|
|
412
|
+
this.ended = true;
|
|
413
|
+
this.serialize(async () => {
|
|
414
|
+
if (generation === this.generation) { await this.release(); }
|
|
415
|
+
}).catch((error: BusinessError) => { this.record(error); });
|
|
416
|
+
if (this.listenerCount > 0) {
|
|
417
|
+
const payload: ExpirationPayload = { generation: generation, reason: reason };
|
|
418
|
+
this.ctx.rnInstance.emitDeviceEvent('expiration', payload);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
override __onDestroy__(): void {
|
|
422
|
+
this.ctx.rnInstance.postMessageToCpp('BACKGROUND_ACTIONS_CLEAR_TIMERS', {});
|
|
423
|
+
this.stop().catch((error: BusinessError) => { this.record(error); });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { RNOHPackage, UITurboModule, UITurboModuleContext } from '@rnoh/react-native-openharmony';
|
|
2
|
+
import { BackgroundActionsModule } from './BackgroundActionsModule';
|
|
3
|
+
import { TM } from './generated/ts';
|
|
4
|
+
export class BackgroundActionsPackage extends RNOHPackage {
|
|
5
|
+
override getUITurboModuleFactoryByNameMap(): Map<string, (ctx: UITurboModuleContext) => UITurboModule | null> {
|
|
6
|
+
return new Map<string, (ctx: UITurboModuleContext) => UITurboModule | null>()
|
|
7
|
+
.set(TM.RNBackgroundActions.NAME, (ctx: UITurboModuleContext) => new BackgroundActionsModule(ctx));
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This code was generated by "react-native codegen-harmony"
|
|
3
|
+
*
|
|
4
|
+
* Do not edit this file as changes may cause incorrect behavior and will be
|
|
5
|
+
* lost once the code is regenerated.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export * as RNC from './components/ts'
|
|
9
|
+
export * as TM from './turboModules/ts'
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This code was generated by "react-native codegen-harmony"
|
|
3
|
+
*
|
|
4
|
+
* Do not edit this file as changes may cause incorrect behavior and will be
|
|
5
|
+
* lost once the code is regenerated.
|
|
6
|
+
*
|
|
7
|
+
* @generatorVersion: 1
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { Tag } from '@rnoh/react-native-openharmony/ts'
|
|
11
|
+
|
|
12
|
+
export namespace RNBackgroundActions {
|
|
13
|
+
export const NAME = 'RNBackgroundActions' as const
|
|
14
|
+
|
|
15
|
+
export type NativeOptions = {
|
|
16
|
+
taskName: string,
|
|
17
|
+
taskTitle: string,
|
|
18
|
+
taskDesc: string,
|
|
19
|
+
taskIcon: TaskIcon,
|
|
20
|
+
color?: string,
|
|
21
|
+
linkingURI?: string,
|
|
22
|
+
progressBar?: ProgressBar,
|
|
23
|
+
foregroundServiceType?: string[],
|
|
24
|
+
harmonyBackgroundModes?: string[],
|
|
25
|
+
generation?: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type ProgressBar = {max: number, value: number, indeterminate?: boolean}
|
|
29
|
+
|
|
30
|
+
export type TaskIcon = {name: string, type: string, package?: string}
|
|
31
|
+
|
|
32
|
+
export type TaskStatus = {
|
|
33
|
+
running: boolean,
|
|
34
|
+
mode: string,
|
|
35
|
+
requestId: number,
|
|
36
|
+
notificationId: number,
|
|
37
|
+
actualDelayTime: number,
|
|
38
|
+
cancelEventsSupported: boolean,
|
|
39
|
+
lastErrorCode: string,
|
|
40
|
+
lastErrorMessage: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface Spec {
|
|
44
|
+
start(options: NativeOptions): Promise<void>;
|
|
45
|
+
|
|
46
|
+
stop(): Promise<void>;
|
|
47
|
+
|
|
48
|
+
updateNotification(options: NativeOptions): Promise<void>;
|
|
49
|
+
|
|
50
|
+
isRunning(): boolean;
|
|
51
|
+
|
|
52
|
+
getStatus(): Promise<TaskStatus>;
|
|
53
|
+
|
|
54
|
+
requestNotifications(): Promise<boolean>;
|
|
55
|
+
|
|
56
|
+
scheduleTimer(id: number, delay: number, repeats: boolean): void;
|
|
57
|
+
|
|
58
|
+
cancelTimer(id: number): void;
|
|
59
|
+
|
|
60
|
+
addListener(eventName: string): void;
|
|
61
|
+
|
|
62
|
+
removeListeners(count: number): void;
|
|
63
|
+
|
|
64
|
+
}
|
|
65
|
+
}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,84 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@hxa-rn/react-native-background-actions",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@hxa-rn/react-native-background-actions",
|
|
3
|
+
"displayName": "@hxa-rn/react-native-background-actions",
|
|
4
|
+
"version": "4.1.1",
|
|
5
|
+
"description": "React Native background service library for running background tasks forever in Android & iOS",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"module": "./src/index.ts",
|
|
8
|
+
"react-native": "./src/index.ts",
|
|
9
|
+
"types": "./src/index.ts",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"private": false,
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://gitcode.com/hxa-rn/react-native-background-actions.git"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"react-native",
|
|
18
|
+
"harmony",
|
|
19
|
+
"harmonyos"
|
|
20
|
+
],
|
|
21
|
+
"homepage": "https://gitcode.com/hxa-rn/react-native-background-actions",
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"registry": "https://registry.npmjs.org/"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist/",
|
|
27
|
+
"src/",
|
|
28
|
+
"harmony/",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"prepare": "tsc --noEmit",
|
|
34
|
+
"codegen-lib": "react-native codegen-harmony --cpp-output-path ./harmony/background_actions/src/main/cpp/generated --ets-output-path ./harmony/background_actions/src/main/ets/generated"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react-native": ">=0.72"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"typescript": "5.0.4",
|
|
41
|
+
"@react-native/typescript-config": "0.79.5",
|
|
42
|
+
"react": "18.2.0",
|
|
43
|
+
"@types/react": "18.2.79",
|
|
44
|
+
"react-native": "0.72.5",
|
|
45
|
+
"jest": "^29.6.3",
|
|
46
|
+
"react-native-builder-bob": "^0.18.0",
|
|
47
|
+
"@react-native-oh/react-native-harmony-cli": "^0.77.50",
|
|
48
|
+
"metro": "^0.81.0",
|
|
49
|
+
"@react-native-oh/react-native-harmony": "0.72.139"
|
|
50
|
+
},
|
|
51
|
+
"engines": {
|
|
52
|
+
"node": ">=18"
|
|
53
|
+
},
|
|
54
|
+
"harmony": {
|
|
55
|
+
"alias": "react-native-background-actions",
|
|
56
|
+
"autolinking": {
|
|
57
|
+
"cmakeLibraryTargetName": "background_actions",
|
|
58
|
+
"ohPackageName": "@hxa-rn/react-native-background-actions",
|
|
59
|
+
"etsPackageClassName": "BackgroundActionsPackage",
|
|
60
|
+
"cppPackageClassName": "BackgroundActionsPackage"
|
|
61
|
+
},
|
|
62
|
+
"codegenConfig": [
|
|
63
|
+
{
|
|
64
|
+
"version": 1,
|
|
65
|
+
"specPaths": [
|
|
66
|
+
"./src/specs/v1"
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
},
|
|
71
|
+
"react-native-builder-bob": {
|
|
72
|
+
"source": "src",
|
|
73
|
+
"output": "dist",
|
|
74
|
+
"targets": [
|
|
75
|
+
"commonjs",
|
|
76
|
+
"module",
|
|
77
|
+
"typescript"
|
|
78
|
+
]
|
|
79
|
+
},
|
|
80
|
+
"dependencies": {
|
|
81
|
+
"eventemitter3": "4.0.7"
|
|
82
|
+
},
|
|
83
|
+
"author": "hxa-rn"
|
|
84
|
+
}
|