# Crash Detection Events

## Usage

Please contact IMS sales to use this feature.

### Prerequisites <a href="#step-by-step-setup" id="step-by-step-setup"></a>

{% hint style="info" %}
If you already have a working integration with the SDK, review the migration guide before reviewing the [#crash-client](#crash-client "mention")
{% endhint %}

Before the Crash Detection feature can be used to detect crashes, the following steps need to be completed:

* [ ] The SDK must be initialized
* [ ] The user must be logged in
* [ ] The phone must be registered
* [ ] Trip detection must be enabled

See the step-by-step guide below for more details <i class="fa-arrow-down-long">:arrow-down-long:</i>

### Step-by-step setup

{% hint style="danger" icon="lightbulb" %}

### **New SDK integrations, expand the section below to review the step-by-step**&#x20;

{% endhint %}

<details open>

<summary><strong>Prerequisites for new SDK integrations</strong> <i class="fa-lightbulb">:lightbulb:</i></summary>

* ### 1. Initialize the SDK <a href="#id-1.-initialize-the-sdk" id="id-1.-initialize-the-sdk"></a>

  Initialize the SDK before any other IMS features can be used.

  \ <a href="/pages/weM7QRFqEP8sMa0NinYc#identity" class="button primary">iOS</a> <a href="/pages/9poclS6REXR85xT419cU#identity" class="button primary">Android</a>\ <br>
* ### 2. Log in the user <a href="#id-2.-log-in-the-user" id="id-2.-log-in-the-user"></a>

  Call `setIdentity` to authenticate the user with the SDK.\
  The **SDK requires an active identity** before trip detection will work as expected.

  \ <a href="/pages/weM7QRFqEP8sMa0NinYc#identity" class="button primary">iOS</a> <a href="/pages/9poclS6REXR85xT419cU#identity" class="button primary">Android</a>\ <br>
* ### 3. Register the device

  The smartphone needs to have been registered through the  `Portal` for successful trip uploading.<br>

  <a href="/pages/NlBEU9Ta92ej8f3GNQbX#device-activation-aka-phone-registration" class="button primary">iOS</a> <a href="/pages/9poclS6REXR85xT419cU#phone-registration-aka-device-activation" class="button primary">Android</a>\ <br>
* ### 4. Enable trip detection

  The app must **initialize the trip detection manager** to record trips; otherwise, Crash Detection will not work.<br>

  <a href="/pages/weM7QRFqEP8sMa0NinYc#beginning-trip-detection-manager" class="button primary">iOS</a>  <a href="/pages/lUD7f2OtFltj0kECJknw#getting-and-setting-the-sdk-configuration" class="button primary">Android</a>     <br>

</details>

{% hint style="danger" icon="octagon-exclamation" %}

### **Existing SDK integrations, expand the section below to review the migration steps needed to unlock the Crash Detection feature.**

Some prerequisite steps require updates for SDK 2.0. The migration guides cover prerequisites and other updates needed to complete the migration. The Crash Detection feature will not work without completing the migration work.​ ​
{% endhint %}

<a href="/pages/wJe1nvQvYvA5rLB7INgJ" class="button primary">Full migration updates for iOS</a> <a href="/pages/MYNoGjV2ZN7iTAYtdb47" class="button primary">Full migration updates for Android</a>

***

## **Crash Detection feature setup**

## Crash Client

Use `CrashClient` to listen for crash events and respond to them within your application.

The `CrashClient` is retrieved by calling `getCrashClient()` , which will return a `CrashClient` provided the crash feature is enabled. This can safely be called more than once; the lifecycle of the `CrashClient` is managed by the SDK.

### Handler registration

Register a handler by calling `startListeningForCrashEvents(onCrash:)` , which will be called whenever a crash event is detected.

```kotlin
// iOS
TripDetectionManager.getCrashClient()

// Android
ImsTripManager.getCrashClient()

protocol CrashClient {
    func startListeningForCrashEvents(onCrash: @escaping (CrashEventData) -> Void)
    func stopListeningForCrashEvents()
    func provideUserFeedback(feedback: CrashUserFeedback)
}
```

## Crash Events

When a potential crash event is detected, the handler registered in `startListeningForCrashEvents()` is called with a `CrashEventData` payload.

#### Crash event data payload

This contains some metadata regarding the crash event, including the computed confidence level defined by our model.

```
CrashEventData {
    crashId: String
    confidence: Int
    speedMps: Double?
    eventTimeEpochNanos: Int?
    latitude: Double?
    longitude: Double?
}
```

| `crashId`             | UUID string that uniquely identifies a given crash event                                                                               |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `confidence`          | A score in the 0 to 100 range representing the likelihood (confidence) that the detected event corresponds to a real vehicle collision |
| `speedMps`            | Measured speed in m/s at the time of crash (optional)                                                                                  |
| `eventTimeEpochNanos` | Time of the crash event, expressed as nanoseconds since the Unix epoch (optional)                                                      |
| `latitude`            | Latitude where the crash occurred (optional)                                                                                           |
| `longitude`           | Longitude where the crash occurred (optional)                                                                                          |

## Handling `Crash Events` & User Notifications

When the SDK detects a crash, your app receives a `CrashEventData` payload via a callback.\
\
A typical integration has three steps:

1. **Start listening** for crash events at an appropriate point in your app's lifecycle (e.g. when trip detection is enabled)
2. **Schedule a local notification** so the user can respond even if the app is backgrounded
3. **Handle the user's response** — either a notification action or a tap through to an in-app screen

### User Notifications

This user feedback data complements the rest of the SDK's collected crash data, helping populate reporting and enabling your claims teams to re*s*olve incidents more efficiently, while also contributing to the long-term accuracy of Crash Detection.\
\
The local notification flow shown here is only one example of how to handle crash events. Your app may use a different approach, such as an in-app modal, a background sync, or a custom review screen.

{% hint style="warning" %}
The core requirement is to receive the `CrashEventData` payload and call `provideUserFeedback` with the user's response.\
\
The surrounding UI is yours to design and build.
{% endhint %}

### Integration steps

{% stepper %}
{% step %}

#### Start listening for Crash Events

Register your crash event handler at an appropriate point in your app's lifecycle.

```swift
// iOS
crashClient.startListeningForCrashEvents { [weak self] crashEventData in
    self?.crashNotificationHandler.scheduleNotification(crashEventData: CrashEventData)
}
```

```kotlin
// Android
crashClient.startListeningForCrashEvents { crashEventData ->
    crashNotificationHandler.scheduleNotification(crashEventData)
}
```

{% endstep %}

{% step %}

#### Configure the Notification Handler

Register your handler once at launch.

**Android**\
This is where you set up the **notification channel**

```kotlin
// Android — create a NotificationChannel
fun configure() {
    // Create notification channel, register actions
}
```

**iOS**\
This is where you set up the **notification delegate** and actions

```swift
// iOS — implement UNUserNotificationCenterDelegate
func configure() {
    // Set delegate, register notification categories/actions
}
```

{% endstep %}

{% step %}

#### Schedule a Notification on Crash

When the SDK reports a crash, build and schedule a local notification.\
Store any data you will need later, in particular the **crash ID**, in the notification payload.

```swift
// iOS
func scheduleNotification(crashEventData: CrashEventData) {
    // Build UNMutableNotificationContent
    // Store crashEventData.crashId in content.userInfo
}
```

```kotlin
// Android
fun scheduleNotification(crashEventData: CrashEventData) {
    // Build a Notification with a PendingIntent
    // Pass crashEventData.crashId as an Intent extra
}
```

{% endstep %}

{% step %}

#### Handle the User's Response

Retrieve the `crashID` from the notification payload, then route based on how the user responded.

<table><thead><tr><th width="187.3333740234375">User action</th><th>How to detect</th><th>What to do</th></tr></thead><tbody><tr><td>Confirmed crash</td><td>Your "confirm" action identifier</td><td>Call <code>provideUserFeedback</code> with <code>.confirmedCrash</code></td></tr><tr><td>Denied crash</td><td>Your "deny" action identifier</td><td>Call <code>provideUserFeedback</code> with <code>.falsePositive</code></td></tr><tr><td>Tapped notification body</td><td>Default tap action</td><td>Navigate to an in-app details screen</td></tr></tbody></table>

To provide user feedback about the crash, construct `CrashUserFeedback` including both the `crashID` from the crash event, as well as the `CrashUserResponse` collected from the user.

```
CrashUserFeedback {
    crashId: String
    feedback: CrashUserResponse
    acknowledgedTimestampEpochNanos: Int?
}

// iOS (Swift)
CrashUserResponse.confirmedCrash
CrashUserResponse.falsePositive

// Android (Kotlin)
CrashUserResponse.CONFIRMED_CRASH
CrashUserResponse.FALSE_POSITIVE
```

```swift
// iOS — UNUserNotificationCenterDelegate
func userNotificationCenter(didReceive response: UNNotificationResponse) {
    let crashId = response.notification.request.content.userInfo["crashId"] as? String

    switch response.actionIdentifier {
    case /* your "confirm" action identifier */:
        crashClient.provideUserFeedback(
            CrashUserFeedback(crashId: crashId, feedback: .confirmedCrash, ...)
        )
    case /* your "deny" action identifier */:
        crashClient.provideUserFeedback(
            CrashUserFeedback(crashId: crashId, feedback: .falsePositive, ...)
        )
    case UNNotificationDefaultActionIdentifier:
        // Navigate to in-app details screen
    default:
        break
    }
}
```

```kotlin
// Android — BroadcastReceiver or Activity handling the PendingIntent
val crashId = intent.getStringExtra("crashId")

when (intent.action) {
    /* your "confirm" action */ ->
        crashClient.provideUserFeedback(
            CrashUserFeedback(crashId = crashId, feedback = CrashUserResponse.CONFIRMED_CRASH, ...)
        )
    /* your "deny" action */ ->
        crashClient.provideUserFeedback(
            CrashUserFeedback(crashId = crashId, feedback = CrashUserResponse.FALSE_POSITIVE, ...)
        )
    else ->
        // Navigate to in-app details screen
}
```

{% endstep %}
{% endstepper %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sdk.ims.tech/crash-detection-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
