Integrate with Android

This section outlines step-by-step instructions to integrate Zendrive SDK into your Android application.

Zendrive provides support for Android 14 (API level 34) from Zendrive SDK v10.1 onwards.

Requirements

  • Zendrive SDK works for Android v5 (API level 21) and above. It will throw a compilation error for applications targeting lower versions.

  • We recommend that if you use Google Play Services, use version 21.0.1.

  • Ensure that your Gradle version is between 7.3.3 and 7.5.

Preparation

  • To use Zendrive SDK, you will need to Sign up or log in to get your key.

  • Upgrade to the latest stable version of Android Studio.

Process Overview

To integrate Zendrive SDK with your application, perform the following steps:

  1. Initialize your application.

  2. Learn how and when to disable the SDK.

Once you have completed the above steps, you are ready to use your application with Zendrive SDK.

Additional Steps

In addition to the above steps, we recommend that you perform the following as well:

  1. Modify the setup for specific features that you may require.

  2. Look at Next Steps.

Starting with SDK 7.1, we provide a default variant and an HMS variant of the Android SDK. If your app requires support for Huawei devices, you will need the HMS variant. See HMS Variant of Android SDK.

If you need support for alternative solutions such as React Native or Xamarin, please contact [email protected].

Add Zendrive SDK to Your Project

1. In your module's build.gradle file, add the following dependencies.

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.zendrive.sdk.android:ZendriveSDK:10.1.0'
}
  1. Specify lintOptions to prevent extraneous lint errors.

  2. Specify packagingOptions to prevent unnecessary files from being included into your application. Your file structure should look like the Complete Sample tab, shown below.

android {
    lintOptions {
        // This is needed to avoid spurious lint errors from libthrift and log4j.
        disable 'InvalidPackage'
    }
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

3. Run gradle sync.

Implement Trip Events

Add the following class to your application. Implement any actions you want to take for each event.

import com.zendrive.sdk.*;
public class MyZendriveBroadcastReceiver extends ZendriveBroadcastReceiver {

    @Override
    public void onDriveStart(Context context, DriveStartInfo startInfo) { ... }

    @Override
    public void onDriveResume(Context context, DriveResumeInfo resumeInfo) { ... }

    @Override
    public void onDriveEnd(Context context, EstimatedDriveInfo estimatedDriveInfo) { ... }

    @Override
    public void onDriveAnalyzed(Context context, AnalyzedDriveInfo analyzedDriveInfo) { ... }

    @Override
    public void onAccident(Context context, AccidentInfo accidentInfo) { ... }

    @Override
    public void onZendriveSettingsConfigChanged(Context context, boolean errorsFound, boolean warningsFound) { ... }

}

Add this broadcast receiver to the manifest before the </application> tag.

<receiver android:name=".MyZendriveBroadcastReceiver" />

More Resources:

Run As a Foreground Service

Your OS may occasionally kill background services, which is why Zendrive uses a foreground service to track a trip when it is in progress. To do this, the SDK asks the application for a required notification.

Add the following class to your application:

import com.zendrive.sdk.*;

public class MyZendriveNotificationProvider extends ZendriveNotificationProvider {

    // Must have a default constructor
    
    @Nullable
    public ZendriveNotificationContainer
        getWaitingForDriveNotificationContainer(@NonNull Context context) { ... }

    @Override
    @RequiresApi(Build.VERSION_CODES.O)
    @NonNull
    public ZendriveNotificationContainer
        getMaybeInDriveNotificationContainer(@NonNull Context context) { ... }

    @Override
    @NonNull
    public ZendriveNotificationContainer
        getInDriveNotificationContainer(@NonNull Context context) { ... }

}

Each of the following notification methods must be implemented according to your needs:

The Notification Container contains the ID and Notification that can be passed to startForeground().

More Resources:

Initialize Zendrive SDK

You would typically do this after the driver logs into the application and you know their identity.

Add Zendrive Imports

import com.zendrive.sdk.*;

Call Zendrive Setup

Upon this call, Zendrive SDK will start automatic trip detection and collect driver data.

Use the <DRIVER_ID> tag below to identify the driver currently using the application. Each driver using the application needs a unique ID.

// Zendrive SDK setup
String zendriveSdkKey = "ZENDRIVE_SDK_KEY";   // Your Zendrive SDK Key

//Optional
ZendriveDriverAttributes driverAttributes = new ZendriveDriverAttributes();
driverAttributes.setAlias("Homer13v2"); // A human recognizable alias for the driver that will be visible in the dashboard
//Vehicle Type: CAR or MOTORCYCLE. Contact us to use.
driverAttributes.setVehicleType(ZendriveVehicleType.CAR);  

ZendriveConfiguration zendriveConfiguration = new ZendriveConfiguration(
    zendriveSdkKey, <DRIVER_ID>);   // a unique id of the driver specific to your application
zendriveConfiguration.setDriverAttributes(driverAttributes);

Zendrive.setup(
    this.getApplicationContext(),
    zendriveConfiguration,
    MyZendriveBroadcastReceiver.class,        // can be null.
    MyZendriveNotificationProvider.class,     // must be non-null.
    new ZendriveOperationCallback() {
        @Override
        public void onCompletion(ZendriveOperationResult result) {
            if (result.isSuccess()) {  ...  }
            else { ... }
        }
    }
);

If the developer doesn't set a dedicated vehicle type during SDK set up, the vehicle type for the trips will be set according to the verdict of the motorcycle detector (if enabled in the SDK configuration. Otherwise the default vehicle type will be Car).

More Resources:

Check for Settings Errors and Warnings

The SDK reports errors and warnings via the onZendriveSettingsConfigChanged(context, errorsFound, warningsFound) callback. This callback is triggered immediately after the SDK is set up, and again whenever there is a change in any settings that affect either trip detection or the normal functioning of the Zendrive SDK.

Zendrive SDK checks for errors or warnings every 2 minutes and triggers this callback only if any setting errors are found.

If the errorsFound flag is true, the SDK has detected setting errors that will affect trip detection. These must be resolved by the application before trip detection can resume.

If the warningsFound flag is true, the SDK has detected warnings. This will cause the SDK to operate but in a degraded mode. For the SDK to function optimally, these warnings should be surfaced to the user for resolution.

As long as errors or warnings exist, the application should call Zendrive.getZendriveSettings(context, callback) to get the list of errors and warnings that must be resolved.

Once all errors and warnings are resolved, the SDK will send an onZendriveSettingsConfigChanged callback with both errorsFound and warningsFound set to false that signals that the SDK has resumed functioning correctly.

The following snippets demonstrate one way of handling this callback.

@Override
public void onZendriveSettingsConfigChanged(Context context, boolean errorsFound, boolean warningsFound) {
    // Persist whether the Zendrive SDK has detected errors or warnings.
    // Use these persisted flags as a basis to determine whether Zendrive settings
    // should be fetched on app resume.
    PreferenceManager.getDefaultSharedPreferences(context).edit().
            putBoolean(Constants.SETTING_ERRORS, errorsFound).
            putBoolean(Constants.SETTING_WARNINGS, warningsFound).apply();
    checkZendriveSettings(context);
}

For more information on the different errors and warnings and handling them correctly, see ZendriveIssueType as well as our sample application.

Disable Zendrive SDK

To disable Zendrive SDK at any point while the application is running, invoke the teardown method. Zendrive SDK goes completely silent after this call and does not track any driving behavior.

Zendrive.teardown(context, new ZendriveOperationCallback() {
        @Override
        public void onCompletion(ZendriveOperationResult result) {
            if (result.isSuccess()) {  ...  }
            else { ... }
        }
    });

Use the teardown method only in appropriate use cases, as in when your end user logs out of your application. See Best Practices for more information.

Add Additional Features

Zendrive SDK provides a number of features that you can use to control how and when trips are detected and where you can implement your business logic, as follows:

Test Your Setup

Before you use the Zendrive SDK, we strongly recommend using our testing framework to simulate drives and perform 'at-desk' integration testing.

Android Testing Framework

Next Steps

Once you finish the steps above, your app now has the Zendrive SDK integrated.

Also see:

Android Checklist and FAQAndroid SDK API ReferenceServer Integrations

Last updated

Was this helpful?