Skip to content

Commit

Permalink
Merge pull request #26 from ionic-team/fix/event-handling
Browse files Browse the repository at this point in the history
fix: Improved Event Handling
  • Loading branch information
markemer authored Aug 9, 2023
2 parents 0c7dde1 + 03d9d0e commit e512c82
Show file tree
Hide file tree
Showing 35 changed files with 931 additions and 679 deletions.
119 changes: 66 additions & 53 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ npx cap sync
```

Background Runner has support for various device APIs that require permission from the user prior to use.

## iOS

On iOS you must enable the Background Modes capability.
On iOS you must enable the Background Modes capability.

![Enable Background Mode Capability in Xcode](https://github.com/ionic-team/capacitor-background-runner/raw/main/docs/enable_background_mode_capability.png)

Once added, you must enable the `Background fetch` and `Background processing` modes at a minimum to enable the ability to register and schedule your background tasks.
Once added, you must enable the `Background fetch` and `Background processing` modes at a minimum to enable the ability to register and schedule your background tasks.

If you will be making use of Geolocation or Push Notifications, enable `Location updates` or `Remote notifications` respectively.

Expand All @@ -26,7 +27,7 @@ After enabling the Background Modes capability, add the following to your app's

```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

// ....
BackgroundRunnerPlugin.registerBackgroundTask()
BackgroundRunnerPlugin.handleApplicationDidFinishLaunching(launchOptions: launchOptions)
Expand All @@ -37,6 +38,7 @@ func application(_ application: UIApplication, didFinishLaunchingWithOptions lau
```

To allow the Background Runner to handle remote notifications, add the following:

```swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// ....
Expand All @@ -52,6 +54,7 @@ func application(_ application: UIApplication, didReceiveRemoteNotification user
```

### Geolocation

Apple requires privacy descriptions to be specified in `Info.plist` for location information:

- `NSLocationAlwaysUsageDescription` (`Privacy - Location Always Usage Description`)
Expand All @@ -62,6 +65,7 @@ Read about [Configuring `Info.plist`](https://capacitorjs.com/docs/ios/configura
## Android

### Geolocation

This API requires the following permissions be added to your `AndroidManifest.xml`:

```xml
Expand All @@ -74,7 +78,8 @@ This API requires the following permissions be added to your `AndroidManifest.xm
The first two permissions ask for location data, both fine and coarse, and the last line is optional but necessary if your app _requires_ GPS to function. You may leave it out, though keep in mind that this may mean your app is installed on devices lacking GPS hardware.

### Local Notifications
Android 13 requires a permission check in order to send notifications. You are required to call `checkPermissions()` and `requestPermissions()` accordingly.

Android 13 requires a permission check in order to send notifications. You are required to call `checkPermissions()` and `requestPermissions()` accordingly.

On Android 12 and older it won't show a prompt and will just return as granted.

Expand All @@ -89,111 +94,119 @@ Note that even if the permission is present, users can still disable exact notif
Read about [Setting Permissions](https://capacitorjs.com/docs/android/configuration#setting-permissions) in the [Android Guide](https://capacitorjs.com/docs/android) for more information on setting Android permissions.

## Using Background Runner
Background Runner is an event based JavaScript environment that emits events to a javascript runner file that you designate in your `capacitor.config.ts` file. If the runner finds a event handler corresponding to incoming event in your runner file, it will execute the event handler, then shutdown once `details.completed()` is called (or if the OS force kills your process).

Background Runner is an event based JavaScript environment that emits events to a javascript runner file that you designate in your `capacitor.config.ts` file. If the runner finds a event handler corresponding to incoming event in your runner file, it will execute the event handler, then shutdown once `resolve()` or `reject()` are called (or if the OS force kills your process).

#### Example Runner JS File

```js
addEventListener("myCustomEvent", (details) => {
console.log("do something to update the system here");
details.completed();
addEventListener('myCustomEvent', (resolve, reject, args) => {
console.log('do something to update the system here');
resolve();
});

addEventListener("myCustomEventWithReturnData", (details) => {
console.log("accepted this data: " + JSON.stringify(details.user));
addEventListener('myCustomEventWithReturnData', (resolve, reject, args) => {
try {
console.log('accepted this data: ' + JSON.stringify(args.user));

const updatedUser = details.user;
updatedUser.firstName = updatedUser.firstName + " HELLO";
updatedUser.lastName = updatedUser.lastName + " WORLD";
const updatedUser = args.user;
updatedUser.firstName = updatedUser.firstName + ' HELLO';
updatedUser.lastName = updatedUser.lastName + ' WORLD';

details.completed(updatedUser);
resolve(updatedUser);
} catch (err) {
reject(err);
}
});

addEventListener("remoteNotification", (details) => {
console.log("received silent push notification");
addEventListener('remoteNotification', (resolve, reject, args) => {
try {
console.log('received silent push notification');

CapacitorNotifications.schedule([
{
CapacitorNotifications.schedule([
{
id: 100,
title: "Enterprise Background Runner",
body: "Received silent push notification",
},
]);

details.completed();
title: 'Enterprise Background Runner',
body: 'Received silent push notification',
},
]);

resolve();
} catch (err) {
reject();
}
});

```
Calling `details.completed()` is **required** within every event handler called by the runner. Failure to do this could result in your runner being killed by the OS if your event is called while the app is in the background. If the app is in the foreground, async calls to `dispatchEvent` may not resolve.

Calling `resolve()` \ `reject()` is **required** within every event handler called by the runner. Failure to do this could result in your runner being killed by the OS if your event is called while the app is in the background. If the app is in the foreground, async calls to `dispatchEvent` may not resolve.

## Configuring Background Runner
On load, Background Runner will automatically register a background task that will be scheduled and ran once your app is backgrounded. The settings for this behavior is defined in your `capacitor.config.ts` file:

On load, Background Runner will automatically register a background task that will be scheduled and ran once your app is backgrounded. The settings for this behavior is defined in your `capacitor.config.ts` file:

```ts
const config: CapacitorConfig = {
plugins: {
BackgroundRunner: {
label: "com.example.background.task",
src: "background.js",
event: "myCustomEvent",
repeat: true,
interval: 2,
autoStart: false,
},
plugins: {
BackgroundRunner: {
label: 'com.example.background.task',
src: 'background.js',
event: 'myCustomEvent',
repeat: true,
interval: 2,
autoStart: false,
},
}
},
};
```


## JavaScript API

Background Runner does not execute your Javascript code in a browser or web view, therefore the typical Web APIs you may be used to may not be available. This includes DOM APIs nor ability to interact with your application's DOM.

Below is a list of the available Web APIs provided in Background Runner:

- [console](https://developer.mozilla.org/en-US/docs/Web/API/console)
- only `info`, `log`, `warn`, `error` , and `debug` are available
- only `info`, `log`, `warn`, `error` , and `debug` are available
- [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder)
- only `decode` is available
- only `decode` is available
- [TextEncoder](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder)
- only `encode` is available
- only `encode` is available
- [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
- Event Listener options and `useCapture` not supported
- Event Listener options and `useCapture` not supported
- [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)
- [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/setInterval)
- [clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout)
- [clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval)
- [crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto)
- [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- Request object not yet supported
- Only `method`, `headers` and `body` supported in options object
- Request object not yet supported
- Only `method`, `headers` and `body` supported in options object

In addition to the standard Web APIs, Background Runner also supports a number of [custom Capacitor APIs](#capacitor-api) custom APIs that expose relevant mobile device functionality



## Runner Lifetimes

Currently, the runners are designed for performing periodic bursts of work while your app is in the background, or for executing asynchronous work in a separate thread from your UI while your app is in the foreground. As a result, runners are not long lived. State is not maintained between calls to events in the runner. Each call to `dispatchEvent()` creates a new context in with your runner code is loaded and executed, and once `completed()` is called, the context is destroyed.
Currently, the runners are designed for performing periodic bursts of work while your app is in the background, or for executing asynchronous work in a thread separate from your UI while your app is in the foreground. As a result, runners are not long lived. State is not maintained between calls to events in the runner. Each call to `dispatchEvent()` creates a new context in which your runner code is loaded and executed, and once `resolve()` or `reject()` is called, the context is destroyed.

## Android Battery Optimizations
Some Android vendors offer built-in battery optimization settings that go beyond what stock Android provides. Some of these optimizations must be disabled by your end users in order for your background tasks to work properly.

Some Android vendors offer built-in battery optimization settings that go beyond what stock Android provides. Some of these optimizations must be disabled by your end users in order for your background tasks to work properly.

Visit [Don't kill my app!](https://dontkillmyapp.com) for more information on the affected manufacturers and steps required by your users to adjust the settings.

## Limitations of Background Tasks

It’s not possible to run persistent, always running background services on mobile operating systems. Due to the limitations imposed by iOS and Android designed to reduce battery and data consumption, background tasks are constrained with various limitations that you must keep in mind while designing and implementing your background task.
It’s not possible to run persistent, always running background services on mobile operating systems. Due to the limitations imposed by iOS and Android designed to reduce battery and data consumption, background tasks are constrained with various limitations that you must keep in mind while designing and implementing your background task.

### iOS

- Each invocation of your task has approximately up to 30 seconds of runtime before you must call `completed()` or your task is killed.
- While you can set an interval to define when your task runs after the app is backgrounded, or how often it should run, this is not guaranteed. iOS will determine when and how often you task will ultimately run, determined in part by how often you app is used.
- While you can set an interval to define when your task runs after the app is backgrounded, or how often it should run, this is not guaranteed. iOS will determine when and how often you task will ultimately run, determined in part by how often you app is used.

### Android

- Your task has a maximum of 10 minutes to perform work, but to keep your task cross platform compatible, you should limit your work to 30 seconds at most.
- Repeating background tasks have a minimal interval of at least 15 minutes. Similar to iOS, any interval you request may not be hit exactly - actual execution time is subject to OS battery optimizations and other heuristics.
- Repeating background tasks have a minimal interval of at least 15 minutes. Similar to iOS, any interval you request may not be hit exactly - actual execution time is subject to OS battery optimizations and other heuristics.

## API

Expand Down Expand Up @@ -304,8 +317,8 @@ Dispatches an event to the configured runner.

</docgen-api>


## Capacitor API

<capacitor-api-docs>

<!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
Expand Down Expand Up @@ -404,4 +417,4 @@ Get access to device location information.
| **`speed`** | <code>number \| null</code> | The speed the user is traveling (if available) | 1.0.0 |
| **`heading`** | <code>number \| null</code> | The heading the user is facing (if available) | 1.0.0 |

</capacitor-api-docs>
</capacitor-api-docs>
6 changes: 3 additions & 3 deletions apps/example-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ const App: React.FC = () => (
<IonTabBar slot="bottom">
<IonTabButton tab="tab1" href="/tab1">
<IonIcon icon={triangle} />
<IonLabel>Tab 1</IonLabel>
<IonLabel>Cap APIs</IonLabel>
</IonTabButton>
<IonTabButton tab="tab2" href="/tab2">
<IonIcon icon={ellipse} />
<IonLabel>Tab 2</IonLabel>
<IonLabel>Core</IonLabel>
</IonTabButton>
<IonTabButton tab="tab3" href="/tab3">
<IonIcon icon={square} />
<IonLabel>Tab 3</IonLabel>
<IonLabel>Wearable</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
Expand Down
Loading

0 comments on commit e512c82

Please sign in to comment.