Skip to content

Initialize the SDK

Before starting to use the functions of Drive Motion SDK, you need to configure the SDK and complete the initialization.

Note

Calling SDK synchronous APIs from the Android main thread is forbidden!

Configuration

The configuration is divided into two parts: the configuration of SDK user information and the configuration of SDK functions. Drive Motion provides SDKOptions and DriveMotionSettings to complete these tasks respectively.

SDKOptions

SDKOptions mainly includes user's basic information and authority information, etc. If you use other SDKs provided by Telenav, you will be able to share SDKOptions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    SDKOptions sdkOptions = SDKOptions.builder()
            .setApiKey("#API_KEY_PROVIDED_BY_TELENAV#")
            .setApiSecret("#API_SECRET_PROVIDED_BY_TELENAV#")
            .setCloudEndPoint("#CLOUD_ENDPOINT_PROVIDED_BY_TELENAV#")
            .setSdkCacheDataDir("#PATH_TO_WRITE_DATA#")
            .setCurrentLocation("#LAST_LATITUDE#", "#LAST_LONGITUDE#")
            .setUserId("#USER_ID#")
            .setDeviceGuid("#DEVICE_ID#")
            .setApplicationInfo(ApplicationInfo.builder("#APPLICATION_NAME#", "#APPLICATION_VERSION#").build())
            .build();
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    val sdkOptions = SDKOptions.builder()
            .setApiKey("#API_KEY_PROVIDED_BY_TELENAV#")
            .setApiSecret("#API_SECRET_PROVIDED_BY_TELENAV#")
            .setCloudEndPoint("#CLOUD_ENDPOINT_PROVIDED_BY_TELENAV#")
            .setSdkCacheDataDir("#PATH_TO_WRITE_DATA#")
            .setCurrentLocation("#LAST_LATITUDE#", "#LAST_LONGITUDE#")
            .setUserId("#USER_ID#")
            .setDeviceGuid("#DEVICE_ID#")
            .setApplicationInfo(ApplicationInfo.builder("#APPLICATION_NAME#", "#APPLICATION_VERSION#").build())
            .build()

Info

SDKOptions provides setCurrentLocation method to set default location at initialization. This location is used as default location when SDK unable to get valid location at startDrive. For example, in tunnels, bunkers, or other places where no GPS signal.

1
    .setCurrentLocation(double latitude, double longitude)

DriveMotionSettings

Use External Data Source

The parameter isUseExternalDataSource in DriveMotionSettings has now been divided into three separate parameters: isUseExternalGPS, UseRoadInfoType, and isUseExternalPhoneUsage. If isUseExternalDataSource is set to true, the corresponding settings should be isUseExternalGPS set to true, UseRoadInfoType set to ADAPTER, and isUseExternalPhoneUsage set to true. It is recommended to use the parameters after the split.

DriveMotionSettings is responsible for some settings on the DriveMotion function. Although all fields are optional, a complete configuration demo is shown below, with each attribute value described in detail in later section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    DriveMotionSettings settings = DriveMotionSettings.builder()
            .withDriveDetectionMode(DriveDetectionMode.AUTO)
            .withBroadcastReceiverClazz(#DRIVE_MOTION_BROADCAST_RECIVER_IMPL_CLASS#)
            .withAlertReceiverClazz(#DRIVE_MOTION_ALERT_RECIVER_IMPL_CLASS#)
            .withRunInBackgroundMode(true) // Optional, default is true
            .withScoringInterval(ScoringInterval.MONTH) // Optional, default is MONTH (30 days)
            .withUseExternalDataSource(false) // Optional, default is false
            .withUseExternalGPS(false) // Optional, default is false
            .withUseRoadInfoType(#UseRoadInfoType#) // Optional, default is INTERNAL
            .withUseExternalPhoneUsage(false) // Optional, default is false
            .withUserAlias(#USER_ALIAS#) // Optional, default is ""
            .withUserState(#USER_STATE#) // Optional, default is ""
            .withOptInRequired(false) // Optional, default is false
            .withDeviceGuidOverrodeByForce(false) // Optional, default is false
            .withExternalUserIdUsedByForce(false) // Optional, default is false
            .withPIIErasure(false) // Optional, default is false
            .withDefaultAnalyticsQueryMode(#QUERY_MODE#) // Optional, default is USER_BASED, added in 2.0
            .withEdgeEventDetectMode(#DETECT_MODE#) // Optional, default is ALL, added in 2.12.0
            .withEnableEdgeMatcher(false) //Optional, default is false, added in 2.16.6
            .withConfigDelegate(#IDriveMotionConfigDelegate#) //Optional, default is null, added in 2.22.0
            .build();
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    val settings = DriveMotionSettings.builder()
            .withDriveDetectionMode(DriveDetectionMode.AUTO)
            .withBroadcastReceiverClazz(#DRIVE_MOTION_BROADCAST_RECIVER_IMPL_CLASS#)
            .withAlertReceiverClazz(#DRIVE_MOTION_ALERT_RECIVER_IMPL_CLASS#)
            .withRunInBackgroundMode(true) // Optional, default is true
            .withScoringInterval(ScoringInterval.MONTH) // Optional, default is MONTH (30 days)
            .withUseExternalDataSource(false) // Optional, default is false
            .withUseExternalGPS(false) // Optional, default is false
            .withUseRoadInfoType(#UseRoadInfoType#) // Optional, default is INTERNAL
            .withUseExternalPhoneUsage(false) // Optional, default is false
            .withUserAlias(#USER_ALIAS#) // Optional, default is ""
            .withUserState(#USER_STATE#) // Optional, default is ""
            .withOptInRequired(false) // Optional, default is false
            .withDeviceGuidOverrodeByForce(false) // Optional, default is false
            .withExternalUserIdUsedByForce(false) // Optional, default is false
            .withPIIErasure(false) // Optional, default is false
            .withDefaultAnalyticsQueryMode(#QUERY_MODE#) // Optional, default is USER_BASED, added in 2.0
            .withEdgeEventDetectMode(#DETECT_MODE#) // Optional, default is ALL, added in 2.12.0
            .withEnableEdgeMatcher(false) //Optional, default is false, added in 2.16.6
            .withConfigDelegate(#IDriveMotionConfigDelegate#) //Optional, default is null, added in 2.22.0
            .build()

DriveDetectionMode

Developers can set DriveDetectionMode to DriveDetectionMode.AUTO or DriveDetectionMode.MANUAL. If it sets to AUTO mode, DriveMotion will automatically detect the start and end of each trip according to a powerful algorithm. Otherwise, the developer needs to use DriveMotionClient API to manually trigger the start and end of the trip.

1
            .withDriveDetectionMode(DriveDetectionMode.AUTO)

DriveMotionBroadcast

DriveMotion provides a broadcast function covering the status changes of the entire trip. When the trip starts, ends, the score changes, and a safety event is detected, the application that uses DriveMotion will receive the corresponding event broadcast. But please note that the premise is to set up a class that extends DriveMotionBroadcastReceiver and configure it according to the following code.

  1. Configure the receiver under the application configuration in AndroidManifest.xml:

    1
        <receiver android:name=".#DRIVE_MOTION_BROADCAST_RECIVER_IMPL#" android:exported="false" />
    
  2. Set it into DriveMotionSettings when initialize:

    1
                .withBroadcastReceiverClazz(#DRIVE_MOTION_BROADCAST_RECIVER_IMPL_CLASS#)
    

DriveMotionAlertReceiver

When using DriveMotion for Driver Assistant feature, users may want to get real time on-screen alert for "high speed" event that impact driving score/rating, so it is more helpful to let user know when to adjust his driving.

  1. Configure the receiver under the application configuration in AndroidManifest.xml:

    1
        <receiver android:name=".#DRIVE_MOTION_ALERT_RECIVER_IMPL#" android:exported="false" />
    
  2. Set it into DriveMotionSettings when initialize:

    1
                .withAlertReceiverClazz(#DRIVE_MOTION_ALERT_RECIVER_IMPL_CLASS#)
    

BackgroundMode

DriveMotion expects to keep running in the background to detect driving behavior more accurately, but if necessary, you can turn it off through the configuration item runInBackgroundMode (default true).

Please note that for mobile applications(especially if there is no Android Framework to keep app alive), please keep run in background enabled, otherwise DriveMotion SDK will not work properly. For head unit launcher with manual detection mode, there is no need to enable running in background mode.

Due to the feature of the Android system, after enabling the background mode, the SDK needs to send a foreground notification to inform the user that the program is running. Please refer to Android Guide for more information on foreground services.

1
            .withRunInBackgroundMode(true)

ScoringInterval

DriveMotion scoring interval (WEEK, FORTNIGHT, MONTH) is time window to calculate cumulative score and sub scores (default is ScoringInterval.MONTH).

1
            .withScoringInterval(ScoringInterval.MONTH)

ExternalDataSource(will deprecated)

DriveMotion external data source is a flag to identify to use Android's native location/sensors or external data (default is false). When set this config to true, external application can using DataSourceClient to feed data to SDK.

1
            .withUseExternalDataSource(false)

ExternalGPS

DriveMotion external GPS is a flag to identify to use Android's native GPS location or external data (default is false). When set this config to true, external application can using DataSourceClient to feed GPS data to SDK.

1
            .withUseExternalGPS(false)

UseRoadInfoType

DriveMotion use road info type is a flag to identify to use road info type INTERNAL, EXTERNAL, ADAPTER or TOGETHER (default is INTERNAL).

When configured as EXTERNAL, external applications can use DataSourceClient to feed road info data to the SDK, disabling internal road info. When configured as ADAPTER, internal road info functions, but if external road info data is fed to the SDK, internal road info will be shutdown. When configured as TOGETHER, internal and external road info work together.

1
            .withUseRoadInfoType(#INTERNAL#)

UseExternalPhoneUsage

DriveMotion external phone usage is a flag to identify to use Android's native sensors or external data (default is false). When set this config to true, external application can using DataSourceClient to feed phone usage data to SDK.

1
            .withUseExternalPhoneUsage(false)

User Opt In Required

Configures whether user must manually opt in auto trip detection or not. Default is false. When set this config to true, external application should use DriveMotionUsersClient to opt in or opt out.

1
            .withOptInRequired(false)

DeviceGuidOverrodeByForce

The DriveMotion SDK uses DeviceGuid to identify the device. Typically, this value is set to ANDROID_ID on Android, but it may need to use a custom value because of the Launcher requirements on head unit projects. The default value is false and the SDK uses the DeviceGuid passed in SDKOptions. If this value is set to true, the SDK overrides DeviceGuid in SDKOptions with ANDROID_ID.

1
            .withDeviceGuidOverrodeByForce(false)

ExternalUserIdUsedByForce

Due to UBI requirements, the DriveMotion SDK needs to use TelematicsUserId to replace the UserId in SDKOptions. If the project does not want to use TelematicsUserId to ensure global user IDs are consistent, set this value to true.

1
            .withExternalUserIdUsedByForce(false)

PIIErasure

It is up to the user/project to allow DriveMotion SDK to capture PII(Personally Identifiable Information) information which is Lat / Lon of the origin / destination. This information must be tied to the device IDs and user IDs provided by the client. If the project want SDK enable remove privacy, set this value to true.

1
            .withPIIErasure(false)

AnalyticsQueryMode

This parameter is used to set the query mode for AnalyticsAPI based on either UserID or DeviceID. The default is "USER_BASED," in this mode, DriveMotion still maintains data isolation between multiple users, and all Analytics interfaces can only query information for the current user. It can be changed to "DEVICE_BASED," in this mode, the SDK will no longer consider user ID as a query condition and will only query Analytics data based on the device ID passed in SDKOptions.

1
            .withDefaultAnalyticsQueryMode(AnalyticsQueryMode.USER_BASED)

EdgeEventDetectMode

This parameter is used to set the event detection mode in edge. "ALL", sdk will detect all Safety events(HA, HB, Speeding), SharpTurn and Distraction event. "SAFETY_ONLY", sdk will only detect Safety event (HA, HB, Speeding). "COACHING_ONLY", sdk will only detect Coaching event (HA, HB, Speeding), SharpTurn and Distraction event. "NONE", sdk will not detect any events.

1
            .withEdgeEventDetectMode(EdgeEventDetectMode.ALL)

EnableEdgeMatcher

This parameter is used to enable/disable trip matcher in edge.

1
            .withEnableEdgeMatcher(false)

DriveMotionConfigDelegate

This parameter is used to provide the capability for DriveMotion SDK to get some configurations dynamically, those configurations might changes while app is running.

1
        .withConfigDelegate(#IDriveMotionConfigDelegate#)

Initialization

The initialize method and shutdown methods need to be called in pair. If initialize failed, please check the following table for details.

Note

  1. If you need to re-initialize the DriveMotion SDK or effect the updated configs, please call DriveMotionService.shutdown() and then DriveMotionService.initialize().
  2. You can use DriveMotionService.isInitialized() API to check whether the SDK initialized or not.

Initialization in synchronous [Deprecated]

Initialization in synchronous is deprecated in release 1.2.1 and will be removed in few releases, please using asynchronous initialization instead.

1
2
3
4
5
6
    try {
        @Deprecated
        DriveMotionService.initialize(MainActivity.this, sdkOptions, settings);
    } catch (DriveMotionException e) {
        // The SDK initialization failed. Please check the message of DriveMotionException and perform subsequent operations according to the message.
    }
1
2
3
4
5
6
    try {
        @Deprecated
        DriveMotionService.initialize(MainActivity.this, sdkOptions, settings)
    } catch (e: DriveMotionException) {
        // The SDK initialization failed. Please check the message of DriveMotionException and perform subsequent operations according to the message.
    }

Initialization in asynchronous

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    DriveMotionService.initialize(MainActivity.this, sdkOptions, settings, new DriveMotionServiceHandler() {
        @Override
        public void handle(boolean isSuccess, @Nullable DriveMotionException exception) {
            if (isSuccess) {
                // Initialize success
            } else {
                // The SDK initialization failed. Please check the message of DriveMotionException and perform subsequent operations according to the message.
            }
        }
    });
1
2
3
4
5
6
7
     DriveMotionService.initialize(MainActivity.this, sdkOptions, settings) { result, e ->
        if (result) {
            // Initialize success
        } else {
            // The SDK initialization failed. Please check the message of DriveMotionException and perform subsequent operations according to the message.
        }
     }

Initialize failed messages

Error Message Root Cause Following Step
"DriveMotionService is already initialized!" Calling initialize when SDK already initialized. No need initialize, or shutdown SDK and then initialize
"DriveMotionService initialize in progress!" Calling initialize when SDK is under initializing. Waiting for exist initialize finish.
"DriveMotionService could not get valid telematics user id." User first login without network or create telematics failed. Check network connectivity and try again.
"DriveMotionService shutdown in progress!" SDK shutdown is under processing. Waiting for shutdown finished and try again.
"SDKOptions validation failed due to #SDKOPTIONS_FIELD_NAME# is null or empty" SDKOptions required field is not filled. Check and fill initialize parameters and try again.
"Failed to initialize DM with #ERROR_MESSAGE#" SDK initialize failed meet exception. Check log, calling shutdown and initialize again.

SDK Auto Initialization

The SDK will attempt to automatically start after device is restarted under AUTO detect mode, and perform initialization based on the parameters which previously passed by initialize.

In order to be able to synchronize the realtime SDK initialization start, please check SDK state by DriveMotionService.isInitialized() before actually calling DriveMotionService.initialize() or DriveMotionService.shutdown().

To re-initialize or update parameters, please call DriveMotionService.shutdown() and then call DriveMotionService.initialize().

Now the SDK is ready to use!

Typical SDK Initialization Configuration

Automatic Trips Detection in Mobile Projects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    private fun dmSettingsAuto(): DriveMotionSettings = DriveMotionSettings.builder()
        // Mark Drive Detection Mode to AUTO
        .withDriveDetectionMode(DriveDetectionMode.AUTO)
        // Register receivers
        .withBroadcastReceiverClazz(SDKBroadcastReceiver::class.java)
        .withAlertReceiverClazz(SDKAlertReceiver::class.java)
        // Enable SDK Foreground Service for running in background
        .withRunInBackgroundMode(true)
        // Config scoring interval as project requirement
        .withScoringInterval(ScoringInterval.FORTNIGHT)
        // Using SDK internal Android Location Manager
        .withUseExternalDataSource(false)
        .withUserAlias("")
        .withUserState("")
        // Config opt in
        .withOptInRequired(false)
        // Config the use of GUID
        .withDeviceGuidOverrodeByForce(true)
        // Config to enable telematics use ID for remove privacy
        .withExternalUserIdUsedByForce(false)
        // Config for remove privacy
        .withPIIErasure(false)
        .build()

Manual Start/Stop Trips in Vehicle Projects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    private fun dmSettingsManual(): DriveMotionSettings = DriveMotionSettings.builder()
        // Mark Drive Detection Mode to MANUAL
        .withDriveDetectionMode(DriveDetectionMode.MANUAL)
        // Register receivers
        .withBroadcastReceiverClazz(SDKBroadcastReceiver::class.java)
        .withAlertReceiverClazz(SDKAlertReceiver::class.java)
        // No need running in background as Launcher is always in foreground
        .withRunInBackgroundMode(false)
        // Config scoring interval as project requirement
        .withScoringInterval(ScoringInterval.FORTNIGHT)
        // Set to "true" to enable feedLocation() and feedRoadInfo()
        .withUseExternalDataSource(true)
        .withUserAlias("")
        .withUserState("")
        // Config opt in
        .withOptInRequired(false)
        // Config the use of GUID
        .withDeviceGuidOverrodeByForce(true)
        // Config to use external user id
        .withExternalUserIdUsedByForce(true)
        // Config for remove privacy
        .withPIIErasure(true)
        .build()

Log Configuration

The DriveMotion SDK allows external applications to customize the logging behavior by configuring basic information before initializing the DriveMotion SDK. In the absence of explicit configuration, the SDK defaults to initializing the log with default settings during the DriveMotion initialization process.

Note

Log initialization must precede DriveMotion SDK initialization to ensure it takes effect.

Initialization SDK Log (Optional)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
        Log.d(TAG, "Initialize Log first.")
        com.telenav.sdk.dataconnector.api.log.Log.initialize(
            #APPLICATION_CONTEXT#,
            #SDK_OPTIONS#,
            ConfigBuilder()
                .setDefaultLogPath(#LOG_FULL_PATH#)
                .setDefaultLogLevel(#LOG_LEVEL#)
                .setLogFilePrefix("LOG_FILE_PREFIX")
                .build()
        )
        Log.d(TAG, "Initialize Log finished with Level INFO.")

initialize need three required params:

  • context: Application Context.
  • options: SDKOptions which same with the one in initialize DriveMotion SDK.
  • configBuilder: Log configs.

Log configs current support the following settings:

** defaultLogPath **

It is supported to specify the root directory where logs will be stored. The logging system will create a directory named "TNLog" within the designated root directory and organize logs into subdirectories.

For example, if the root directory is set to context.filesDir.toString(), the logs will be stored internally in the following path: /data/data/$PACKAGE_NAME$/files/TNLog.
Similarly, if the root directory is set to context.getExternalFilesDir(null), the logs will be stored externally in the path: /sdcard/Android/data/$PACKAGE_NAME$/files/TNLog.
Alternatively, the application can specify a custom directory to store logs. However, it is crucial for the application to ensure that it has granted write permissions for the specified directory.

** defaultLogLevel **

It is supported to specify the SDK printable log level by set defaultLogLevel.

Dynamic Printable Log Level Update

Throughout the application's runtime, the external application has the flexibility to dynamically modify the log level using the following API:

1
        com.telenav.sdk.dataconnector.api.log.Log.setLogLevel(Log.INFO)

This interface allows the application to adjust the log level as needed. For example, setting the log level to INFO enables the printing of INFO, WARN, and ERROR level logs while filtering out VERBOSE and DEBUG level logs.