# Crash Detection

{% hint style="info" %}
The Vehicle Crash Detection feature must be enabled for your app by Sentiance, before you can start using it. Please reach out to our support team to enable the feature.
{% endhint %}

## App Integration

Follow the below steps to set up vehicle crash detection in you app.

### 1. Integrate the Sentiance SDK

If you haven't already integrated the Sentiance SDK, follow the steps in our [Getting Started](https://docs.sentiance.com/a-complete-integration/getting-started) guide to complete the integration. Once you have completed those steps, continue along with the steps documented below.

### 2. \[Android Only] Add the Crash Detection Dependency

To support crash detection, add a dependency to the crash detection library artifact in your app. This will make the `CrashDetectionApi` class available for you to subscribe for crash events.

{% code title="app/build.gradle" %}

```groovy
dependencies {
    implementation(platform('com.sentiance:sdk-bom:<sentiance-version>'))
    implementation('com.sentiance:sdk-crash-detection')
    ...
}
```

{% endcode %}

### 3. Check if Vehicle Crash Detection Is Supported

There are several reasons why vehicle crash detection may not be supported on the device. The two most common of these are:

* the feature is not enabled for your app;
* the device lacks the necessary sensors (e.g. accelerometer).

You can check to see whether vehicle crash detection is support on the device, as follows.

{% tabs %}
{% tab title="Android" %}

```kotlin
CrashDetectionApi.getInstance(context).isVehicleCrashDetectionSupported
```

{% endtab %}

{% tab title="iOS" %}

```objectivec
Sentiance.shared.isVehicleCrashDetectionSupported
```

{% endtab %}

{% tab title="React Native" %}

```javascript
import { 
    isVehicleCrashDetectionSupported 
} from '@sentiance-react-native/crash-detection';

const result = isVehicleCrashDetectionSupported();
```

{% endtab %}

{% tab title="Flutter" %}

```dart
import 'package:sentiance_crash_detection/sentiance_crash_detection.dart';

final sentianceCrashDetection = SentianceCrashDetection();
bool result = await sentianceCrashDetection.isVehicleCrashDetectionSupported();
```

{% endtab %}
{% endtabs %}

### 4. Subscribe for Vehicle Crash Events

In order to be notified of vehicle crash events, you must set a listener that the SDK can invoke whenever it detects vehicle crashes.

{% tabs %}
{% tab title="Android" %}

```java
CrashDetectionApi.getInstance(context).setVehicleCrashListener(new VehicleCrashListener() {
    @Override
    public void onVehicleCrash(VehicleCrashEvent crashEvent) {
        // Handle the vehicle crash event

        long epochTimeMs = crashEvent.getTime();
        Location location = crashEvent.getLocation();
        Float speedAtImpact = crashEvent.getSpeedAtImpact();
        Float magnitude = crashEvent.getMagnitude();
        Float deltaV = crashEvent.getDeltaV();
        Integer confidence = crashEvent.getConfidence();
        VehicleCrashSeverity severity = crashEvent.getSeverity();
    }
});
```

{% endtab %}

{% tab title="iOS" %}

```swift
Sentiance.shared.setVehicleCrashHandler { crashEvent in
    let date = crashEvent.date
    let confidence = crashEvent.confidence
    let deltaV = crashEvent.deltaV
    let magnitude = crashEvent.magnitude
    let speedAtImpact = crashEvent.speedAtImpact
    let location = crashEvent.location
    let severity = crashEvent.severity
}
```

{% endtab %}

{% tab title="React Native" %}

```javascript
import { 
    addVehicleCrashEventListener 
} from '@sentiance-react-native/crash-detection';

addVehicleCrashEventListener(crashEvent => {
    const time = crashEvent.time;
    const location = crashEvent.location;
    const magnitude = crashEvent.magnitude;
    const speedAtImpact = crashEvent.speedAtImpact;
    const deltaV = crashEvent.deltaV;
    const confidence = crashEvent.confidence;
    const severity = crashEvent.severity;
});
```

{% endtab %}

{% tab title="Flutter" %}
Create a **background.dart** file under your project's **lib** folder with the following code:

{% code title="background.dart" %}

```dart
import 'package:sentiance_crash_detection/sentiance_crash_detection.dart';

@pragma('vm:entry-point')
void registerCrashDetectionListener() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Subscribe for vehicle crash events
  SentianceCrashDetection.registerCrashListener((crashEvent) {
    // Handle the vehicle crash event

    final epochTimeMs = crashEvent.time;
    final location = crashEvent.location;
    final speedAtImpact = crashEvent.speedAtImpact;
    final magnitude = crashEvent.magnitude;
    final deltaV = crashEvent.deltaV;
    final confidence = crashEvent.confidence;
    final severit = crashEvent.severity;
  });
  
  // Subscribe for diagnostic information
  SentianceCrashDetection.registerCrashDiagnosticListener((diagnostic) {
    final state = diagnostic.crashDetectionState;
    final description = diagnostic.crashDetectionStateDescription;
  });
}
```

{% endcode %}

Add the following code, depending on your target platform.&#x20;

For **iOS**, add the following to your app delegate class:

{% code title="AppDelegate.swift" %}

```swift
import Flutter
import sentiance_crash_detection

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
    
        // Other code
        
        SentianceCrashDetectionPlugin.initializeListener(
            withEntryPoint: "registerCrashDetectionListener",
            libraryURI: "package:your_app_package_name/background.dart"
        )
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

{% endcode %}

For **Android**, add this code to your custom application class:

{% code title="MainApplication.kt" %}

```kotlin
import android.app.Application
import com.sentiance.crash_detection_plugin.CrashDetectionPlugin

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Other code

        val dartLibrary = "package:your_app_package_name/background.dart"
        CrashDetectionPlugin.initializeListener(this, dartLibrary, "registerCrashDetectionListener")
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

The crash event contains the time and location of the detected crash, in addition to a number of metrics to estimate the severity of the crash:

<table data-header-hidden><thead><tr><th width="199"></th><th></th></tr></thead><tbody><tr><td>Speed at impact</td><td>The estimated speed of the vehicle before the impact, in m/s.</td></tr><tr><td>Magnitude</td><td>The magnitude of the impact, in Gs.</td></tr><tr><td>Delta-V</td><td>The estimated change in velocity at impact, in m/s.</td></tr><tr><td>Confidence</td><td>The level of confidence that the accelerometer signal reflects a true crash pattern (range 0 - 100). It is recommended to filter out events below the confidence of 50.</td></tr><tr><td>Severity</td><td>A categorical severity of the crash (low, medium, high).</td></tr></tbody></table>

### 5. Test Your Integration

The final step is checking your integration, to make sure that your vehicle crash listener is properly set up to handle crash events. Add the following method call in your app to trigger a dummy crash event.

{% tabs %}
{% tab title="Android" %}

```java
CrashDetectionApi.getInstance(context).invokeDummyVehicleCrash();
```

{% endtab %}

{% tab title="iOS" %}

```swift
Sentiance.shared.invokeDummyVehicleCrash()
```

{% endtab %}

{% tab title="React Native" %}

```javascript
import { 
    invokeDummyVehicleCrash 
} from '@sentiance-react-native/crash-detection';

invokeDummyVehicleCrash();
```

{% endtab %}

{% tab title="Flutter" %}

```dart
import 'package:sentiance_crash_detection/sentiance_crash_detection.dart';

final sentianceCrashDetection = SentianceCrashDetection();
await sentianceCrashDetection.invokeDummyVehicleCrash();
```

{% endtab %}
{% endtabs %}

This should invoke a dummy crash event, passing it to the listener that you previously set. You can then test how your app handles the event at runtime.

It's also possible to subscribe for additional diagnostic information that the SDK outputs at runtime, and receive a human-readable form of the state of the crash detector, which can be used to facilitate testing, when simulating a crash.

{% tabs %}
{% tab title="Android" %}

```kotlin
CrashDetectionApi.getInstance(context).setVehicleCrashDiagnosticListener { diagnostic ->
    val state = diagnostic.crashDetectionState
    val description = diagnostic.crashDetectionStateDescription
}
```

{% endtab %}

{% tab title="iOS" %}

```swift
Sentiance.shared.setVehicleCrashDiagnosticHandler { diagnostic in
    let state = diagnostic.crashDetectionState
    let description = diagnostic.crashDetectionStateDescription
}
```

{% endtab %}

{% tab title="React Native" %}

```javascript
await SentianceCrashDetection.addVehicleCrashDiagnosticListener(diagnostic => {
    const state = diagnostic.crashDetectionState;
    const description = diagnostic.crashDetectionStateDescription;
}
```

{% endtab %}

{% tab title="Flutter" %}
Please check the previous "**Subscribe for Vehicle Crash Events**" section on how to subscribe for diagnostic information along with vehicle crash events for Flutter.
{% endtab %}
{% endtabs %}

The result will reflect one of the following detection states:

* crash candidate detected
* crash candidate discarded - impact is too weak
* crash candidate discarded - transport mode is not a vehicle
* crash candidate discarded - pre-impact signal contains too much noise
* crash candidate discarded - speed before impact is too low
* crash candidate discarded - post-impact signal contains too much noise
* crash candidate discarded - speed after impact is too high
