# Initialization

## Init

The Android MOVE SDK must be initialized by adding MoveSdk.init() at the first line in your Android Application class (onCreate). This instance can then be used to control MOVE SDK services.

After the MOVE SDK has been initialized you also want to add notifications, listeners or activate additional features.

Also you have to configure the MOVE SDK before you are able to call .setup(...).

```kotlin
// your application class

override fun onCreate() {
   // init the MOVE SDK
   val moveSdk = MoveSdk.init(this)   
   
   super.onCreate()

   // Example of adding some notifications, register listener
   // and activate MOVE SDK features.
   moveSdk.apply {
     recognitionNotification(recognitionNotification)
     tripNotification(drivingNotification)
     sdkStateListener(sdkStateListener)
     tripStateListener(tripStateListener)
     authStateUpdateListener(authStateListener)
     initializationListener(initListener)
     setServiceErrorListener(errorListener)
     setServiceWarningListener(warningListener)
     initiateAssistanceCall(assistanceListener)
     deviceDiscoveryListener(deviceDiscoveryListener)
     consoleLogging(true)
   }
   
   // ... continue with Config ...
}
```

By clicking the links below you can find further information about the usage.

* [recognitionNotification](#dolphinsdk.builderv1.1-recognitionnotificationrecognitionnotifications)
* [tripNotification](#trip-notifications)
* [sdkStateListener](#dolphinsdk.builderv1.1-sdkstatelistenersdkstatelistener)
* [tripStateListener](#trip-state-listener)
* [authStateUpdateListener](#dolphinsdk.builderv1.1-initializationinitializationlistener-1)
* [initializationListener](#dolphinsdk.builderv1.1-initializationinitializationlistener)

Used Services in the example above and [more](https://docs.movesdk.com/move-platform/sdk/api-interface/android/services):

* [setServiceErrorListener](https://docs.movesdk.com/move-platform/sdk/api-interface/services#set-service-error-listener)
* [setServiceWarningListener](https://docs.movesdk.com/move-platform/sdk/api-interface/services#set-service-warning-listener)
* [initiateAssistanceCall](https://docs.movesdk.com/move-platform/sdk/api-interface/services#initiate-assistance-call)
* [consoleLogging](https://docs.movesdk.com/move-platform/sdk/api-interface/services#console-logging)
* [deviceDiscoveryListener](https://docs.movesdk.com/move-platform/sdk/api-interface/services#set-device-discovery-listener)

## Config <a href="#config" id="config"></a>

Whenever you are ready to start the Move SDK, setup() needs to be called with a proper configuration. The following code sample demonstrates a common configuration with driving, walking, cycling, automatic impact detection and assistance call.

```kotlin
   // ... Init ...
   
   // Example of a configuration of the MOVE SDK
   val moveServices: MutableSet<MoveDetectionService> = mutableSetOf()
   
   val drivingServices: MutableSet<DrivingService> = mutableSetOf()
   drivingServices.add(DrivingService.DrivingBehaviour)
   drivingServices.add(DrivingService.DistractionFreeDriving)
   drivingServices.add(DrivingService.DeviceDiscovery)

   val walkingServices: MutableSet<WalkingService> = mutableSetOf()
   walkingServices.add(WalkingService.Location)

   moveServices.add(MoveDetectionService.Driving(drivingServices = drivingServices.toList()))
   moveServices.add(MoveDetectionService.Walking(walkingServices = walkingServices.toList()))
   moveServices.add(MoveDetectionService.Cycling)
   moveServices.add(MoveDetectionService.AutomaticImpactDetection)
   moveServices.add(MoveDetectionService.AssistanceCall)
   
   val moveConfig = MoveConfig(moveDetectionServices = moveServices.toList())
   
   // ... continue with Setup ...
```

## Setup

{% hint style="warning" %}
It is recommended to set up notifications before calling the setup() method.
{% endhint %}

{% hint style="warning" %}
It is recommended that .setup(...) is called **ONLY ONCE!**

If .shutdown() was called before then .setup(...) must be redone.
{% endhint %}

### With MoveAuth

{% hint style="warning" %}
Deprecated in the future. The new approach is by using an authCode. see [Setup with authCode](#with-authcode)
{% endhint %}

The data for the MoveAuth object must be fetched using the given project’s API Key (see [MOVE Backend - Example request](https://docs.movesdk.com/move-platform/backend/example-requests#create-a-new-user)).

```kotlin
.setup(
    auth: MoveAuth, 
    config: MoveConfig,
    start: Boolean?,
    options: MoveOptions?
)
```

<table data-header-hidden><thead><tr><th width="263.3333333333333">Parameter</th><th width="220"></th><th>Description</th></tr></thead><tbody><tr><td>auth</td><td><a href="../../models/moveauth">MoveAuth</a></td><td>The user's Auth object. (see <a href="../../../../backend/example-requests#create-a-new-user">MOVE Backend - Create a new user</a>) </td></tr><tr><td>config</td><td><a href="../../models/moveconfig">MoveConfig</a></td><td>The move configuration</td></tr><tr><td>start</td><td>Boolean</td><td>optional:<br>Default: <strong>true</strong> ->  <a href="../services#start-automatic-detection">startAutomaticDetection()</a> is called automatically<br><br><strong>false</strong> -> you have to call <a href="../services#start-automatic-detection">startAutomaticDetection()</a> manually</td></tr><tr><td>options</td><td><a href="../../models/moveoptions">MoveOptions</a></td><td>optional: added with v2.3.+</td></tr></tbody></table>

{% hint style="warning" %}

### SDK Authentication

Passing the authentication config is **required** for each setup. The host app is also responsible for monitoring the [AuthState](https://docs.movesdk.com/move-platform/sdk/models/moveauthstate) changes.
{% endhint %}

{% hint style="warning" %}
If you want to use startTrip(...) ([**Manual Start Trip**](https://docs.movesdk.com/move-platform/sdk/api-interface/services#manual-start-trip)) you have to pass **false** to the parameter **start**.
{% endhint %}

### With authCode

The authCode must be fetched using the userId (see [MOVE Backend - Example request](https://docs.movesdk.com/move-platform/backend/example-requests#create-a-new-user)).

```kotlin
.setup(
    authCode: String, 
    config: MoveConfig,
    start: Boolean?,
    options: MoveOptions?,
    callback: MoveAuthCallback
)
```

<table data-header-hidden><thead><tr><th width="263.3333333333333">Parameter</th><th width="220"></th><th>Description</th></tr></thead><tbody><tr><td>authCode</td><td>String</td><td>The authCode received from the backend. (see <a href="../../../../backend/example-requests#create-a-new-user">MOVE Backend - Create a new user</a>) </td></tr><tr><td>config</td><td><a href="../../models/moveconfig">MoveConfig</a></td><td>The move configuration</td></tr><tr><td>start</td><td>Boolean</td><td>optional:<br>Default: <strong>true</strong> ->  <a href="../services#start-automatic-detection">startAutomaticDetection()</a> is called automatically<br><br><strong>false</strong> -> you have to call <a href="../services#start-automatic-detection">startAutomaticDetection()</a> manually</td></tr><tr><td>options</td><td><a href="../../models/moveoptions">MoveOptions</a></td><td></td></tr><tr><td>callback</td><td>MoveAuthCallback</td><td>This listener will report the success or failure during the internal MOVE SDK authentication process. (see <a href="../../models/moveauthresult">MoveAuthResult</a>)</td></tr></tbody></table>

#### Example of implementing the MoveAuthCallback:

```kotlin
private val moveAuthCallback = object : MoveSdk.MoveAuthCallback {
    override fun onResult(result: MoveAuthResult) {
        when (result.status) {
            AuthSetupStatus.SUCCESS -> {
                // Do something if the result is SUCCESS.
            }
            AuthSetupStatus.INVALID_CODE -> {
                // Do something if the result is INVALID_CODE.
            }
            AuthSetupStatus.NETWORK_ERROR -> {
                // Do something if the result is NETWORK_ERROR.
            }
        }
    }
}
```

## Listeners

### Initialization listener <a href="#dolphinsdk.builderv1.1-initializationinitializationlistener" id="dolphinsdk.builderv1.1-initializationinitializationlistener"></a>

Block that gets invoked on initialization completion with error. On error, [MoveConfigurationError](https://docs.movesdk.com/move-platform/models/moveconfigurationerror#android) is returned. On success, the [MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate) will change accordingly.

```kotlin
.initializationListener(listener: MoveInitializeListener)
```

| Parameter |                                                                                                             | Description                                                                                                                                                                    |
| --------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| listener  | [InitializeListener](https://docs.movesdk.com/move-platform/models/listeners-callbacks#initialize-listener) | <p>Block that gets invoked on initialization completion with error. On error, </p><p><a href="../../models/moveconfigurationerror">MoveConfigurationError</a> is returned.</p> |

### Auth state update listener <a href="#dolphinsdk.builderv1.1-initializationinitializationlistener" id="dolphinsdk.builderv1.1-initializationinitializationlistener"></a>

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

```swift
.authStateUpdateListener(callback: AuthStateUpdateListener)
```

| **Callback**            |                                                                                                                                 |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| AuthStateUpdateListener | 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`authStateUpdateListener`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 %}

### MOVE SDK State listener <a href="#dolphinsdk.builderv1.1-sdkstatelistenersdkstatelistener" id="dolphinsdk.builderv1.1-sdkstatelistenersdkstatelistener"></a>

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

{% hint style="warning" %}
The host app is expected to be monitoring [MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes so it can start the SDK services when [MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate) is`.ready`or handle errors if occurred.
{% endhint %}

```kotlin
.sdkStateListener(listener: MoveSdkStateListener)
```

| Parameter |                                                                                                                  | Description                                                                                                         |
| --------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| listener  | [MoveSdkStateListener](https://docs.movesdk.com/move-platform/models/listeners-callbacks#movesdk-state-listener) | Block gets called whenever the [MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes. |

### Trip state listener

```kotlin
.tripStateListener(listener: MoveTripStateListener)
```

| Parameter |                                                                                                                | Description                                                                                                                                                                                                           |
| --------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| listener  | [MoveTripStateListener](https://docs.movesdk.com/move-platform/models/listeners-callbacks#trip-state-listener) | A listener where [`onTripStateChanged`](#DolphinSdk.Builderv1.1-tripstatelistenerTripstatelistener) gets called whenever the [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) changes |

### Trip notifications

Passes a notification builder which is used to create a notification reaching places and walking paths. For more information on that please check[ notification management](https://docs.movesdk.com/move-platform/sdk/appendix/android/notification-managment).

```kotlin
.tripNotification(notification: Notification.Builder)
```

| Parameter    | Description                                        |
| ------------ | -------------------------------------------------- |
| notification | The notification builder to build the notification |

### Walking notifications

Passes a notification builder which is used to create a notification for places and walking paths. For more information on that please check[ notification management](https://docs.movesdk.com/move-platform/sdk/appendix/android/notification-managment).

```kotlin
.walkingNotification(notification: Notification.Builder)
```

| Parameter    | Description                                        |
| ------------ | -------------------------------------------------- |
| notification | The notification builder to build the notification |

### Recognition notifications <a href="#dolphinsdk.builderv1.1-recognitionnotificationrecognitionnotifications" id="dolphinsdk.builderv1.1-recognitionnotificationrecognitionnotifications"></a>

Passes a notification  builder which is used to create notification while detecting activities, trips and more. For more information on that, please check[ notification management](https://docs.movesdk.com/move-platform/sdk/appendix/android/notification-managment).

<pre class="language-kotlin"><code class="lang-kotlin"><strong>.recognitionNotification(notification: Notification.Builder)
</strong></code></pre>

| Parameter    | Description                                        |
| ------------ | -------------------------------------------------- |
| notification | The notification builder to build the notification |

### Trip Metadata <a href="#dolphinsdk.builderv1.2-metadatametadata" id="dolphinsdk.builderv1.2-metadatametadata"></a>

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. This metadata will be forwarded back along with the trip when fetched by the client-server, so the host app can utilize it in its app. Note: The MOVE SDK will not use this metadata element in any way, it is just passed through to the project.

The block provides the trip's start and stop times. Make sure to only include metadata events that are collected inside the given start and end periods.

```kotlin
.metadataProvider(provider: TripMetadataProvider)
```

| Parameter                                                                                            | Description                                                                                                          |
| ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| [provider](https://docs.movesdk.com/move-platform/models/listeners-callbacks#trip-metadata-provider) | Callback to provide a bundle of key-value pairs to a trip. The trip is represented with a given start and stop time. |

## Initialization

Tries to initialize the MOVE SDK. You can only have one initialized MOVE SDK at a time. If you have a MOVE SDK instance already, consider calling [`shutdown`](https://docs.movesdk.com/move-platform/sdk/api-interface/services#shutdown-sdk)before.\
The initialization process is asynchronous and the host app is expected to register a [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) [`listener`](#DolphinSdk.Builderv1.1-sdkstatelistenerSdkstatelistener) to monitor successful initialization and start services when [MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate) transits to`READY` . The host app should also monitor [`initialization listener`](#DolphinSdk.Builderv1.1-initializationInitializationlistener) to handle potential [MoveConfigurationError](https://docs.movesdk.com/move-platform/sdk/models/moveconfigurationerror).

{% hint style="warning" %}

### Application Context

Make sure to pass the application context
{% endhint %}

| Parameter | Description               |
| --------- | ------------------------- |
| context   | Main application context. |

```kotlin
fun init(context: Context): MoveSdk
```

| **Return** |                             |
| ---------- | --------------------------- |
| MoveSdk    | The instance of the MoveSdk |

| **Throws**                     |                                                                 |
| ------------------------------ | --------------------------------------------------------------- |
| MissingAuthenticationException | If the passed configuration is missing, e.g. empty access token |

{% hint style="info" %}
If you have already successfull initialized the MOVE SDK once, try to initialize the MOVE SDK next time in your application in [onCreate](https://developer.android.com/reference/android/app/Application#onCreate\(\)). This ensures that the MOVE SDK can do its work whenever the application is restarted after termination.
{% endhint %}
