# Services

```javascript
import MoveSdk from 'react-native-move-sdk';
```

## **Detection Services**

### **Start Automatic Detection**

Starts the required detection services stated in the [MoveConfig](https://docs.movesdk.com/move-platform/sdk/models/moveconfig) passed on initialization. Starting the service will set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) to `.running`.

```typescript
MoveSdk.startAutomaticDetection(): Promise<boolean>
```

Promise will be resolved with ***false*** if the SDK is not in `.ready` state.

### **Stop Automatic Detection**

Stops the automatic detection service, including all SDK services like driving detection, points of interest, walking and places. Stopping the service will set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) back to `.ready`.&#x20;

```typescript
MoveSdk.stopAutomaticDetection(): Promise<boolean>
```

Promise will be resolved with ***false*** if the SDK is not in `.running` state.

### **Force Trip Recognition**

Temporarily calibrates the SDK to the highest detection mode.

In order to optimize battery consumption, the SDK goes through different detection modes with different battery consumption levels, depending on the user's current behavior and activity. In general, the SDK is responsible for alternating between those different detection modes.&#x20;

The SDK also provides hosting apps this API to call if they have their own reasons (like buttons, sensors or beacons) to believe that the user is starting a trip. This will make sure the SDK is on the highest detection state to detect the trip faster.

```javascript
MoveSdk.forceTripRecognition(): void
```

### **Finish Current Trip**

Ends the current ongoing trip.

This API will end the ongoing trip and set [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) back to `.idle`. The SDK is responsible for detecting the trip start and end points. The SDK also provides hosting apps this API to call if they have their own reasons (like sensors or beacons) to believe that the user's trip has ended.

{% hint style="warning" %}
**Precondition**:[ MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) should be in an active trip.
{% endhint %}

```javascript
MoveSdk.finishCurrentTrip(): void
```

{% hint style="info" %}
If this API is called while the user is active on a driving trip, a new trip will start again right away. If the intention is to un-track the ongoing trip, call `ignoreCurrentTrip`API.

More information about trip states can be found in [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate).
{% endhint %}

### **Ignore Current Trip**

Ignores the current ongoing trip.&#x20;

This API will set the ongoing [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) to `.ignored`. Data of ignored trips is purged and not sent to the server.

{% hint style="warning" %}
**Precondition**: [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) should be in an active trip.
{% endhint %}

```javascript
MoveSdk.ignoreCurrentTrip(): void
```

### **Set Trip Metadata**

{% hint style="info" %}
Since MOVE SDK v2.8.0
{% endhint %}

Add key-value pairs to be appended to the trip metadata before the trip finishes.

Host apps can use this API to add any app-level information (for ex. Bluetooth beacon detected, foreground/background time, etc) to append to a trip as metadata (only for current trip, when the next trip starts old metadata is removed). This metadata will be forwarded back along with the trip when fetched by the client-server. Note: The SDK will not use this metadata element in any way, it is just passed through to the project environment.

<pre class="language-typescript"><code class="lang-typescript"><strong>MoveSdk.setTripMetadata(metadata?: { [key: string]: string }): void
</strong></code></pre>

### **Manual Start Trip**

{% hint style="info" %}
Since MOVE SDK v2.8.0
{% endhint %}

Manually force the start of a trip, bypassing trip validation checks. This non-standard SDK usage may be feasible only in situations where active user input can be expected. Using the metadata parameter, self-defined information can be added to each trip which can be fetched from the [timeline](https://docs.movesdk.com/move-platform/backend/move-backend/move-timeline-api#trip-metadata).

```typescript
startTrip(metadata?: { [key: string]: string} ): Promise<boolean>
```

Promise will be resolved with ***false*** if the SDK is not in `.ready` state.

{% hint style="warning" %}
**Precondition**: MOVE SDK must be in`READY`[MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate).

Manually starting a trip bypasses additional trip detection checks. Manually started trips must be ended with [`finishCurrentTrip()`](#finish-current-trip)

It is recommended not to use [MoveOptions](https://docs.movesdk.com/move-platform/models/moveoptions#ios) *`motionPermissionMandatory`* o&#x72;*`backgroundLocationPermissionMandatory`*`with` this API, as they will be ignored.
{% endhint %}

## Processing Services

### **Keep in foreground (Android only)**

When an Android application is in the background it may receive limited data (location, sensors, etc.). To improve this behaviour, it is possible to put the application always in the foreground with a visible notification that cannot be discarded. Just because it's visible it doesn't mean that it is performing any data collection at all. So this should not have any significant battery impact at all.

{% hint style="info" %}
Disabled by default. Since it may be annoying to the user, it should only be enabled in case of problems.
{% endhint %}

```javascript
MoveSdk.keepInForeground(enabled: boolean): void
```

### **Keep active (Android only)**

To save battery consumption, the SDK is using several triggers to start its data listeners. In case of trouble, these triggers can be circumvented by allowing the MoveSdk to stay active all the time. In that case the SDK is always monitoring required data and is therefore consuming more battery. Depending on the configuration, it may happen that the notification (see[ notification handling](https://docs.movesdk.com/move-platform/sdk/appendix/android/notification-managment)) is always visible to the user.

{% hint style="info" %}
Disabled by default. Since this is consuming more battery, it should only be enabled in case of problems.
{% endhint %}

```javascript
MoveSdk.keepActive(enabled: boolean): void
```

### **Get SDK State**

Gets the current[ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate).

```typescript
MoveSdk.getState(): Promise<SdkState>
```

### Get Trip State

Get the current [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate).

```typescript
MoveSdk.getTripState(): Promise<TripState>
```

### Get Auth State

Get the current [MoveAuthState](https://docs.movesdk.com/move-platform/sdk/models/moveauthstate).

```typescript
MoveSdk.getAuthState(): Promise<AuthState>
```

### Get Errors

Get the current list of [MoveServiceFailure](https://docs.movesdk.com/move-platform/sdk/models/moveservicefailure).

```typescript
MoveSdk.getErrors(): Promise<ErrorListType>
```

### Get Warnings

Get the current list of [MoveServiceFailure](https://docs.movesdk.com/move-platform/sdk/models/moveservicefailure).

```typescript
MoveSdk.getWarnings(): Promise<WarningListType>
```

### **Set SDK State Listener**

Provide a block to be invoked every time [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes.

{% hint style="info" %}
Set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) listener before initializing the SDK to anticipate the SDK [State](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes triggered by the initialization API. \
Here the host app can start the SDK services when [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) is`.ready`or handle errors if occurred.
{% endhint %}

{% hint style="warning" %}
For android platform it is necessary to start listen explicitly by calling:

```typescript
if (Platform.OS === 'android') {
    MoveSdk.startNativeSdkStateListener();
}
```

{% endhint %}

```javascript
MoveSdk.addSdkStateListener(sdkStateChanged: (state: SdkState) => void): ListenerSubscription;
```

| **Callback**    |                                                                                                                                                                                                                                  |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sdkStateChanged | Block that gets invoked every time[ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) is changed and provides the updated [ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate). |

### **Set SDK Auth State Listener**

Provide a block to be invoked every time [MoveAuthState](https://docs.movesdk.com/move-platform/sdk/models/moveauthstate) changes.

```javascript
MoveSdk.addAuthStateListener(authStateChanged: (event: AuthStateEvent) => void): ListenerSubscription;
```

| **Callback**     |                                                                                                                                 |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| authStateChanged | Block that gets invoked every time [MoveAuthState](https://docs.movesdk.com/move-platform/sdk/models/moveauthstate) is updated. |

{% hint style="warning" %}

### Authentication Expiry

The host app is expected to monitor [MoveAuthState](https://docs.movesdk.com/move-platform/sdk/models/moveauthstate) updates via`authStateUpdateListene` API and handle those changes accordingly.

Check [Authentication updates and expiry](https://docs.movesdk.com/move-platform/models/moveauthstate#authentication-updates-and-expiry) for more details about authentication expiry and renewal.
{% endhint %}

### **Set Trip State Listener**

Provide a block to be invoked every time [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) changes.

```javascript
MoveSdk.addTripStateListener(tripStateChanged: (state: TripState) => void): ListenerSubscription;
```

| Callback         |                                                                                                                                                                                                                                             |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| tripStateChanged | Block that gets invoked every time  [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) is changed and provides the updated  [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate). |

### Set Errors Listener

Provide a block to be invoked every time [MoveServiceFailure](https://docs.movesdk.com/move-platform/sdk/models/moveservicefailure) changes.

```javascript
MoveSdk.addErrorsListener(errorsReceived: (errors: ErrorListType) => void): ListenerSubscription;
```

### Set Warnings Listener

Provide a block to be invoked every time [MoveServiceWarning](https://docs.movesdk.com/move-platform/sdk/models/moveservicewarning) changes.

```javascript
MoveSdk.addWarningsListener(warningsReceived: (warnings: ErrorListType) => void): ListenerSubscription;
```

### **Set Log Listener**

Add a log listener for debugging.

```typescript
static addLogListener(logReceived: (event: MoveSdkLog) => void): ListenerSubscription;
```

### **Shutdown SDK**

Shutdown SDK shared instance.

{% hint style="warning" %}
**Precondition:** SDK must be initialized.
{% endhint %}

Stops SDK services, send the queued user data, and de-initializes the SDK. After that is executed,  the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) will transit to `.uninitialized`.

{% hint style="info" %}
If it's necessary just to stop all SDK services you most likely need to use [stopAutomaticDetection](https://docs.movesdk.com/move-platform/sdk/api-interface/react-native/services#stop-automatic-detection) instead of shutdown. Use shutdown in case of user's logout, SDK auth error (in those cases where you know for sure that you will need to execute [MoveSdk.setup](https://docs.movesdk.com/move-platform/sdk/api-interface/react-native/initialization#javascript) with new [MoveAuth](https://docs.movesdk.com/move-platform/sdk/models/moveauth#react-native) object, for example).
{% endhint %}

```javascript
MoveSdk.shutdown(force:boolean = true): Promise<ShutdownReturnType>
```

<table data-header-hidden><thead><tr><th width="196.66666666666669"></th><th width="137"></th><th></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td><strong>Default</strong></td><td></td></tr><tr><td>force</td><td>true</td><td>If true, <em>shutdown</em> executes immediately. Pending Data may be lost and always returns with a success, see <a href="../../../models/moveshutdownresult#react">ShutdownReturnType</a> otherwise.</td></tr></tbody></table>

{% hint style="danger" %}
When `force: false` is specified the shutdown may fail when pending data cannot be uploaded and reject the promise (status code: `NETWORK_ERROR`) which needs to be handled.
{% endhint %}

### Resolve Error

```typescript
MoveSdk.resolveError(): void
```

### **Synchronize User Data**

Used to force synchronizing user data with the SDK server. Limited to once per 2 minutes.

```javascript
MoveSdk.synchronizeUserData(): void
```

## Other Services

### Initiate Assistance Call

*New feature in MOVE SDK 2.x; configuration in MOVE dashboard pending - please* [*get in touch*](mailto:info@dolph.in?subject=MOVE%20SDK)*.*

Initiate an assistance call to emergency services.

```typescript
MoveSdk.initiateAssistanceCall(): Promise<boolean>
```

Returns a promise with a [MoveAssistanceCallStatus](https://docs.movesdk.com/move-platform/models/moveassistancecallstatus#android).

{% hint style="warning" %}
**Precondition:** The assistance call service needs to be configured in the MOVE dashboard. The SDK needs to be in *ready* or *running* state.
{% endhint %}

### Set Assistance MetaData

{% hint style="info" %}
Since MOVE SDK 2.1.0
{% endhint %}

```typescript
MoveSdk.setAssistanceMetaData(data: string): void
```

<table><thead><tr><th width="281.3333333333333"></th><th width="176"></th><th></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td></td><td></td></tr><tr><td><pre><code>data
</code></pre></td><td>String</td><td>A string to be sent with each assistance call or impact</td></tr></tbody></table>

The metadata string is set once, and then sent to the server with each and every manual assistance call and with AID report. The contents of the string can be anything, e.g. JSON data. The assistance data is persisted once set.

### Set Timer (Android only)

{% hint style="info" %}
Since MOVE SDK v2.7.0
{% endhint %}

```typescript
MoveSdk.setTimer(callback: () => void, delay?: number): string
```

Usual setTimeout doesn't work if app is in the background on Android. The SDK provides **setTimer** that works in the same way as setTimeout, but also in the background. A call to `setTimer` returns a “timer identifier” that we can use to cancel the execution via [`cancelTimer`](#cancel-timer-android-only).

<table><thead><tr><th></th><th></th><th width="103"></th><th></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td><strong>Default</strong></td><td></td><td></td></tr><tr><td>delay</td><td>60000</td><td>number</td><td>Delay in miliseconds.</td></tr><tr><td>callback</td><td></td><td>function</td><td>Callback that will be executed after delay.</td></tr></tbody></table>

### Cancel Timer (Android only)

{% hint style="info" %}
Since MOVE SDK 2.7.0
{% endhint %}

```typescript
MoveSdk.cancelTimer(key: string): void
```

This method removes timer that was added via [`setTimer`](#set-timer-android-only).

|                |        |                                                        |
| -------------- | ------ | ------------------------------------------------------ |
| **Parameters** |        |                                                        |
| key            | string | "Timer identifier" which was returned from `setTimer`. |

### Live Location TAG

{% hint style="info" %}
Since MOVE SDK 2.8.0
{% endhint %}

```typescript
MoveSdk.setLiveLocationTag(tag?: string): Promise<boolean>
```

Adds a Tag to trip events. This Tag information is added to the timeline data. To clear the Tag do not pass parameter.

After a `shutdown(...)` ([Android](https://docs.movesdk.com/move-platform/sdk/android/services#shutdown-sdk) / [iOS](#shutdown-sdk)) the Tag is also cleared.

<table><thead><tr><th width="160"></th><th width="549"></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td></td></tr><tr><td>tag</td><td>String <code>[a-z] [0-9]</code> and <code>null</code> to clear the Tag.</td></tr></tbody></table>

<table><thead><tr><th width="161"></th><th></th></tr></thead><tbody><tr><td><strong>Return values</strong></td><td></td></tr><tr><td>true</td><td>Live Location Tag is applied.</td></tr><tr><td>true</td><td>Live Location Tag is cleared (no parameter is passed).</td></tr><tr><td>false</td><td>Live Location Tag exceeds the limit of 200 characters.</td></tr><tr><td>false</td><td>Live Location Tag is blank or empty.</td></tr><tr><td>false</td><td>If the passed chars are not one of these [a-z] [0-9].</td></tr></tbody></table>

## Configuration services

### Update authentication

Updates SDK [MoveAuth](https://docs.movesdk.com/move-platform/sdk/models/moveauth). On SDK auth expiry, the authStateListener will trigger expired state. The host app is expected to fetch a new [MoveAuth](https://docs.movesdk.com/move-platform/sdk/models/moveauth) using its project API key and pass it to the MoveSDK using the following API:

```jsx
MoveSdk.updateAuth(auth: MoveSdkAuth): Promise<void>
```

<table><thead><tr><th width="186.4285714285714">Parameters</th><th width="150"> </th></tr></thead><tbody><tr><td>auth</td><td>The user's updated Auth object with the new token.</td></tr></tbody></table>

### Update config

{% hint style="info" %}
Since MOVE SDK v2.8.0
{% endhint %}

Change the [MoveConfig](https://docs.movesdk.com/move-platform/sdk/models/moveconfig) originally passed in setup. Optionally update the [MoveOptions](https://docs.movesdk.com/move-platform/models/moveoptions#react-native) passed in setup.

```typescript
MoveSdk.updateConfig(config: MoveSdkConfig, options?: MoveSdkOptions): Promise<boolean>
```

## Device Discovery

{% hint style="danger" %}
Due to limitations in Android’s Classic Bluetooth APIs, reliable connection status tracking may not always be possible. For more details and available workarounds, see [Forcing the Signal - Classic Bluetooth](https://docs.movesdk.com/move-platform/sdk/appendix/android/forcing-the-signal-classic-bluetooth).
{% endhint %}

### Start Scanning Devices

Start scanning for devices which can be registered on the SDK for trip device discovery. A block will get invoked each time new devices are found.

```tsx
MoveSdk.startScanningDevices(sdkDevicesDetected: (state: Array<MoveSdkDevice>) => void, filter: MoveSdkDeviceFilter[], uuid?: string, manufacturerId?: number): ListenerSubscription;
```

<table><thead><tr><th width="208">Parameters</th><th width="194.33333333333334"></th><th></th></tr></thead><tbody><tr><td>sdkDevicesDetected</td><td>Listener</td><td>Block that gets invoked every time a new <a href="../../../models/movedevice#react">MoveSdkDevice</a>  is detected.</td></tr><tr><td>filter</td><td>MoveSdkDeviceFilter</td><td>Filter devices by type.  See bellow.</td></tr><tr><td>uuid</td><td>string</td><td>UUID String required to scan beacons.</td></tr><tr><td>manufacturerId</td><td>number</td><td>Manufacturer ID needed to scan beacons.</td></tr></tbody></table>

Returns a subscription object. Scanning will stop automatically when the subscription is removed, otherwise the scan will continue and this will impact device battery usage.

A list of filters can be specified to filter which devices to scan for:

<table><thead><tr><th width="193">MoveDeviceFilter</th><th></th></tr></thead><tbody><tr><td>paired</td><td>Scan for paired devices. <strong>Default</strong></td></tr><tr><td>connected</td><td>Scan for connected devices. <em>New since version 2.10.4</em>.</td></tr><tr><td>beacon</td><td>Scan for beacon devices. <code>uuid</code> and <code>manufacturerId</code> required.</td></tr></tbody></table>

### Set MoveDevice Connection State Listener

{% hint style="info" %}
Since MOVE SDK v2.10.0
{% endhint %}

Set a [MoveDevice](https://docs.movesdk.com/move-platform/models/movedevice#react-native) connection state listener to be fired when the Bluetooth connection state of a previously registered [MoveDevice](https://docs.movesdk.com/move-platform/models/movedevice#react-native) has changed.

```typescript
MoveSdk.addDeviceStateListener(onScanResult: (results: Array<MoveSdkDevice>) => void): ListenerSubscription;
```

| **Parameters**                                                                                                                              |                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| listener -> [MoveDeviceStateListener](https://docs.movesdk.com/move-platform/models/listeners-callbacks#movedevice-state-listener-callback) | A callback returning the [MoveDevice](https://docs.movesdk.com/move-platform/models/movedevice#react-native) which connection state was changed. |

### Get Registered Devices

Get a list of devices ([MoveSdkDevice](https://docs.movesdk.com/move-platform/models/movedevice#react)) registered to be discovered during trips.

```tsx
MoveSdk.getRegisteredDevices(): Promise<Array<MoveSdkDevice>>;
```

### Register Devices

Register devices ([MoveSdkDevice](https://docs.movesdk.com/move-platform/models/movedevice#react)) to be discovered during trips.

```tsx
MoveSdk.registerDevices(devices: Array<MoveSdkDevice>): Promise<boolean>;
```

### Unregister Devices

Unregister devices (MoveSdkDevice) to be discovered during trips.

```tsx
MoveSdk.unregisterDevices(devices: Array<MoveSdkDevice>): Promise<boolean>;
```

{% hint style="info" %}
Since MOVE SDK v2.13: Devices are persisted after [shutdown](#shutdown-sdk).
{% endhint %}

### Discover Devices

```tsx
MoveSdk.addDeviceDiscoveryListener(onScanResult: (results: Array<MoveScanResult>) => void): ListenerSubscription;
```

Subscribe to updates for registered devices scanned during trips. See [MoveScanResult](https://docs.movesdk.com/move-platform/models/movescanresult#react).

### Set Health Score Listener

Provide a block to be invoked every time MoveHealthScore[ ](https://docs.movesdk.com/move-platform/models/moveservicewarning#android)will change.

```typescript
MoveSdk.addHealthListener(scoreReceived: (health: MoveHealthScore) => void): ListenerSubscription
```

<table data-header-hidden><thead><tr><th width="260.3333333333333"></th><th></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td></td></tr><tr><td><a href="../../../models/listeners-callbacks#react-native-11">MoveHealthScoreListener</a></td><td>Block that get's invoked when the health score changes.</td></tr></tbody></table>

### **Set Remote Config Change Listener**&#x20;

{% hint style="info" %}
Since MOVE SDK v2.5
{% endhint %}

Provide a block to be invoked every time [MoveConfig](https://docs.movesdk.com/move-platform/models/moveconfig#react-native) was successfully fetched from the server.

```typescript
MoveSdk.addRemoteConfigChangeListener(configChangeReceived: (config: Array<IssueListService>) => void): ListenerSubscription
```

| **Parameters** |                                                                          |
| -------------- | ------------------------------------------------------------------------ |
| listener       | A callback returning a List of services after a successful server fetch. |

### **Get Configuration**

Gets the current used Move configuration set in setup/update or configuration. If options flag `useBackendConfig` is set returns configuration set in dashboard.&#x20;

{% hint style="info" %}
Since MOVE SDK v2.16
{% endhint %}

```typescript
MoveSdk.getMoveConfig(): Promise<MoveSdkConfig>;
```

| **Return**                                                                 |                                                                                                        |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [MoveConfig](https://docs.movesdk.com/move-platform/sdk/models/moveconfig) | Move Configuration passed in setup/update or configuration from backend if *useBackendConfig* is set.. |

### **Step Counter**

{% hint style="info" %}
Since MOVE SDK v2.14
{% endhint %}

See section [Permission Handling](https://docs.movesdk.com/move-platform/sdk/appendix/react-native/permission-handling) in Appendix.

For Android please see the section [**Step Counter (via Google Health Connect)**](https://docs.movesdk.com/move-platform/sdk/android/services#step-counter-via-google-health-connect)
