Interacting with Kruzr SDK

In this section we discuss some specific and frequently used methods which is relevant for any driving app. These methods help you interact with our Kruzr 360 Platform, helping you improve user experience and also build new features on top of them.

Broadly, we will cover 3 key points which involve such interactions:

  1. Trip Controls with manual override options for your users

  2. Trip List and Current Trip Detail access from our cloud to your app - using which you can create engaging illustrations and driver engagement programs

  3. Data Sync Preference which help you control WIFI or WIFI + Cellular Data syncs for trip files on your app.

Location and Activity permissions are most important aspect of any driving app. It ensures that app is able to automatically detect user trips, score them properly and ensure that data quality is reliable. Therefore, for promised quality of service you need to make absolutely sure that your users have provided the required permissions.

Start Trip Manually

Manual Start Trip method is a useful way to provide your users with control over starting the trip themselves if they prefer it over Automatic Trip Detection. It also helps you make your app more complete in terms of possible user flows.

You can provide extra trip details through ClientTripExtras in the form of JSONObject so that additional information can be provied to Kruzr platform for analytics and reporting purposes.

Please note that Manual Trip Start will throw following failure callback states which refer to the following conditions:

  • USER_AUTHORISATION_FAILURE If this is the case, please call registerUser() method again

  • ALREADY_IN_TRIP This means that a pre-existing trip is already going on. Please stop the ongoing trip using stopTrip() method and call start trip again to start a new trip (a single device can only have one live trip session)

try {
    Kruzr.getInstance().startTrip(this, clientTripExtras , new TripStartCallback() {
        
        @Override        
        public void onTripStartSuccess() {
        }
        
        @Override        
        public void onTripStartFailure(TripStartFailure tripStartFailure) {
            switch (tripStartFailure){
                case ALREADY_IN_TRIP:
                    //Pre-existing trip is already going on
                    break;
                    
                case USER_AUTHORISATION_FAILURE:
                    //If this is the case, please call registerUser() method again
                    break;
            }
        }
    });
} catch (PermissionsMissingException e) {
    /**
     *   Exception will be thrown if user has not granted permission for location
     *   Ask location permission from user
     */
}

PermissionsMissingException will be thrown if user has not granted permission for location, that is Manifest.permission.ACCESS_FINE_LOCATION. You can use this exception to prompt the user via your app to provide you with required location permission. Details can be found here - https://developer.android.com/training/permissions/requesting

Stop Trip Manually

Allows the user to manually end an ongoing trip. Please note that the trip may be automatically started or manually started - in either of the cases, an on-going trip can be terminated/stopped using this method.

Note: Within the Kruzr system, it is not a mandatory implementation since all on-going trips are Auto-Stopped via SDK if driving movement has stopped. However, providing option of manual override is preferable since it provides more control to your users over their trips

TripStop will throw the following exceptions:

  • NO_ONGOING_TRIP: If no trip is in progress against the DRIVER_ID

Kruzr.getInstance().stopTrip(this, new TripStopCallback() {
    
    @Override
    public void onTripStopSuccess() {
    }
    
    @Override
    public void onTripStopFailure(TripStopFailure tripStopFailure) {
        switch (tripStopFailure){
            case NO_ONGOING_TRIP:
                //No trip is in progress
                break;
        }
    }
});

Share Trip

*Country Code List & Phone Number List are 1 to 1 mapped.

*App Trip ID of the current trip can be obtained by calling getTripData You can find the method below.

Please call shareTrip method with the following parameters -

  • context

  • appTripId- App Trip ID of the trip you want to share.

  • countryCodeList - list of country code. ex ["+91","+001"]

  • phoneNumberList - list of phone numbers.

  • TripShareCallback to listen for success or failure

Kruzr.getInstance().shareTrip(context, appTripId, countryCodeList, phoneNumberList, new TripShareCallback() {
   
   @Override
   public void onTripShareSuccess(ShareTripResponseModel shareTripResponseModel) {
   }
   
   @Override
   public void onError(String errorDetails) {
   }
});

Get Trip List

Trip list provides your app a method to fetch all the trips for a particular user within your app.

Please call fetchTripList method with the following parameters -

  • context

  • offset - the starting point/reference from which you need to fetch trips.

  • limit - how many trips you want to be fetched

  • TripListCallbackInterface to listen for success or failure

Kruzr.getInstance().fetchTripList(context, offset, limit, new TripListCallbackInterface() {
   
   @Override
   public void onTripListFetch(ArrayList<SingleTripResponseModel> arrayList) {
   }
   
   @Override
   public void onError(ErrorModel errorModel) {
   }
});

It is recommended as to use combination of limit and offset while loading trip lists for users in your app. It will help you reduce the need making bulk downloads of all trips, specially in cases where number of trips for the user is very high. So, for example, if you want to fetch 12 trips between position 30 and 42, you will set offset as 30 and limit as 12.

Get Details of Current Trip

Please call getTripData method, passing context as a parameter to get details for an on-going trip. You can use this information to engage drivers for their ongoing trips.

Note that if the user is not taking a trip then this will return null.

Kruzr.getInstance().getTripData(context);

Get Details of Completed Trip

Please call fetchTripDetailByTripId method with the following parameters to get details for a completed trip. You can use this information to generate trip summary pages and illustrations on historical/completed trips of users.

  • context

  • TRIP_ID - TripID of the trip you want to fetch details for

  • SingleTripCallbackInterface to listen for success or failure

Kruzr.getInstance().fetchTripDetailByTripId(mContext, "TRIP_ID", new SingleTripCallbackInterface() {
   
   @Override
   public void onSingleTripDataFetch(SingleTripResponseModel singleTripResponseModel) {
   }

   @Override
   public void onError(ErrorModel errorModel) {
   }
});

Get Trip Stats of Completed Trip

(Support added since 2.3.0 version of SDK)

Please call getTripStats method with the following parameters to get trip stats for a completed trip. You can use this information to generate trip summary pages of users.

  • context

  • TRIP_ID - TripID of the trip you want to fetch details for

  • TripStatsCallbackInterface to listen for success or failure

Kruzr.getInstance().getTripStats(mContext, "TRIP_ID", new TripStatsCallbackInterface() {
   
   @Override
   public void onTripStatsFetch(TripStats tripStats) {
   }

   @Override
   public void onError(ErrorModel errorModel) {
   }
});

Trip Stats

{
 extraTripScores : {
 hardAcceleration :: double,
 hardBraking :: double,
 hardTurn :: double,
 speeding :: double,
 drowsy :: double,
 hardAccelerationStarRating :: int,
 hardBrakingStarRating :: int,
 hardTurnStarRating :: int,
 speedingStarRating :: int,
 drowsyStarRating :: int,
 
}

Mark trip as Co-Passenger.

(Support added since 2.4.1 version of SDK)

Use this method to update your recorded trip and designate it as a co-passenger trip. This functionality is particularly useful when you need to distinguish auto-detected trips in which you were not the driver.

Kruzr.getInstance().wasCoPassengerInTrip(mContext, "TRIP_ID", new CoPassengerStateUpdateCallback() {
   
   @Override
   public void onSuccess() {
   }

   @Override
   public void onFailure(String error) {
   }
});

Parameters:

  • mContext: The context required for the operation.

  • "TRIP_ID": The unique identifier of the trip you want to mark as a co-passenger trip.

  • CoPassengerStateUpdateCallback: The callback to handle the success or failure of the update.


Setting Preference for Trip Data Sync

You can define the preferences/settings if you would like to sync trip data of your users via WiFi ONLY or both, WiFi + Mobile Data. These implementations help you provide flexibility to your users on their data consumption and can be customized based on use case requirements. You can also use these on "App Settings" page to your users so that they can decide which sync method they want to set.

Please call setDataSyncPref method with the following parameters:

  1. context

  2. dataSync, which can take one of these values -

    1. DataSync.WIFI_ONLY,

    2. DataSync.WIFI_OR_CELLULAR;

Kruzr.getInstance().setDataSyncPref(context, dataSync);

Getting Current Data Sync Preference

As a business or product analysis requirement, you may need to classify/keep track of the current data sync setting a user has provided your app with - specially if you have implemented setDataSyncPref as a user controlled setting within your app.

Please call getCurrentDataSyncPref method, passing context as a parameter to get this value. This method will return the currently set data sync preference, which will be either DataSync.WIFI_ONLY or DataSync.WIFI_OR_CELLULAR.

Kruzr.getInstance().getCurrentDataSyncPref(Context context);

Manual Sync Trip Data

We have provide auto-syncing of trip data after a trip completes. But incase the android os prevents this, there is always an alternate method to manually sync the data.

Kruzr.getInstance().syncTripData(Context context)

Real Time Data sync while on Trip

Kruzr captures and sends realtime location data while the user is on trip. You can turn off this feature through this method. All location data are still captured locally and processed post trip.

Note that disabling real time data sync also disables GPS pings which is needed for contextual scoring and real time vehicle tracking use cases. Please only turn this off when these two use cases are not relevant for your business.

Kruzr.getInstance().allowEventSyncRealTime(Context context, boolean value)

You can check the current status of this feature through this method

Kruzr.getInstance().getEventSyncRealTimeStatus(Context context)

That's all for now! You have successfully implemented all available methods using Kruzr Android SDK into your app. Please keep checking the updates section for developer notes on upcoming additions to our SDK!

Added in 2.4.0.beta.1

Leaderboard Details

Call getLeaderboardUsers method with the following parameters to get details of the leaderboard.

Suppose you want to fetch users on the leaderboard with rank from position 16 to 25. Then offset will be 16 and limit will be 25-16 = 9.

  • limit - how many users to fetch

  • offset - from which position should users be fetched

  • LeaderboardUsersInterface to listen for success or failure

Kruzr.getInstance().getLeaderboardUsers(limit, offset, new LeaderboardUsersInterface() {
      
      @Override
      public void onLeaderboardUsersFetchSuccess(List<LeaderboardUser> list) {
      }

      @Override
      public void onLeaderboardUsersFetchFailure(String s) {
      }
});

LeaderboardUser object

LeaderboardUser {
    int rank;
    String username;
    Float averageTripScore;
    int totalTripCount;
}

Ranking details of current user

Call getCurrentUserLeaderboardRanking method with the following parameter to get ranking details of the current user.

  • UserRankingDetailsInterface to listen for success or failure

Kruzr.getInstance().getCurrentUserLeaderboardRanking(new UserRankingDetailsInterface() {
      
      @Override
      public void onUserRankingFetchSuccess(UserRankingDetails userRankingDetails) {
      }

      @Override
      public void onUserRankingFetchFailure(String failureReason) {
      }
});

You will get the registered drivers rank details in the following format.

UserRankingDetails {
    String currentRank;
    String percentile;
    Double averageTripScore;
    Int totalCount;
}

Metrics Data

This section contains the methods to get aggregated data for a particular period of date ranges.

These methods are supported from SDK version 2.5.0.alpha.1

You might need to use the dates in few of the API's. Here is an example to create a date of format 3 December 2023. Our methods assumes the date to be in UTC, so make sure to do the necessary conversion at your end.

// Create a Calendar instance and set the desired year, month, and day
Calendar calendar = Calendar.getInstance();
calendar.set(2023, 11, 3); // Month is 0-based (11 represents December)

// Convert the Calendar instance to a Date
Date date = calendar.getTime();

You will be getting most of the aggregation methods response in KruzrHistoricDoubleDataResponse

KruzrHistoricData {
    Double? data: 
    String startDate: String
    String endDate: 
}
KruzrHistoricDoubleDataResponse{
    Double? data: 
    [KruzrHistoricData] historicData:
}
MetrixPeriodicalType can be of the following types DAILY, WEEKLY or MONTHLY

Get Registered Driver Details

Call getRegisteredDriver method with the following parameter to get information about the registered driver passed at the time of registration along with their total trip count, total drive time (in Seconds), total distance travelled (in KM) and average driving score.

Kruzr.getInstance().getRegisteredDriver(this, new RegisteredDriverDetailsCallback() {
            @Override
            public void onSuccess(RegisteredDriver registeredDriver) {
                
            }

            @Override
            public void onError(String s) {

            }
        });

You will get the registered driver details in the following format.

class RegisteredDriver {
    String companyName;
    String countryCode;
    String driverID;
    String email;
    String name;
    String phoneNumber;
    
    Double averageTripScore;
    Double totalDistanceTravelled;
    Int totalTripCount;
    Double totalTripDurationInSeconds;
}

Get Aggregated Driving Score for a particular duration

Call getAggregatedDrivingScore method with the following parameter to get the average driving score of the registered driver.

Kruzr.getInstance().getAggregatedDrivingScore(Date startDate,Date endDate, MetrixPeriodicalType periodicalType,new MetricsDataInterface<Double>() {
            @Override
            public void onSuccess(KruzrHistoricDoubleDataResponse aggregatedDrivingScore) {
                
            }

            @Override
            public void onFailure(String failureMessage) {
                
            }
        });

Get Aggregated Driving Distance for a particular duration

Call getAggregatedDistanceTravelled method with the following parameter to get the distance driven in KM by the current registered driver.

Kruzr.getInstance().getAggregatedDistanceTravelled(Date startDate, Date endDate, MetrixPeriodicalType periodicalType, new MetricsDataInterface<Double>() {
            @Override
            public void onSuccess(KruzrHistoricDoubleDataResponse aggregatedDistanceTravelled) {
                
            }

            @Override
            public void onFailure(String failureMessage) {
                
            }
        });

Get Aggregated Driving Time in seconds for a particular duration

Call getAggregatedDriveTimeInSeconds method with the following parameter to get duration driven in seconds by the current registered driver.

Kruzr.getInstance().getAggregatedDriveTimeInSeconds(Date startDate, Date endDate, MetrixPeriodicalType periodicalType, new MetricsDataInterface<Double>() {
            @Override
            public void onSuccess(KruzrHistoricDoubleDataResponse aggregatedDriveTimeInSeconds) {
                
            }

            @Override
            public void onFailure(String failureMessage) {
                
            }
        });

Get Aggregated Driving Score for a particular duration

Call getAggregatedDrivingBehaviourScore method with the following parameter to get individual driving behaviour score of the current registered driver.

Kruzr.getInstance().getAggregatedDrivingBehaviourScore(Date startDate, Date endDate, MetrixPeriodicalType periodicalType, new MetricsDataInterface<DrivingBehaviourScore>() {
            @Override
            public void onSuccess(DrivingBehaviourScore aggregatedDrivingBehaviourScore) {
                
            }

            @Override
            public void onFailure(String failureMessage) {
                
            }
        });

You will get the response in the following format.

Currently this method is still under maintenance. We will return null for the respective score if we are unable to fetch that parameter. We will soon be adding the error message in the onFailure callback.

class DrivingBehaviourScore {
    Double hardAcceleration;
    List<KruzrHistoricData> historicHardAcceleration;
    Double speeding;
    List<KruzrHistoricData> historicSpeeding
    Double braking;
    List<KruzrHistoricData> historicBraking
    Double laneChange;
    List<KruzrHistoricData> historicLaneChange
    Double hardTurn;
    List<KruzrHistoricData> historicHardTurn
    Double fatigue;
    List<KruzrHistoricData> historicFatigue
}

Added in 3.3.4

Get Driving Summary for a particular duration

Call getDrivingSummary method with the following parameter to get individual driving summary of the current registered driver.


Kruzr.getInstance().getDrivingSummary(Date startDate,Date endDate, new MetricsDataInterface<DrivingSummary>() {
            @Override
            public void onSuccess(DrivingSummary drivingSummary) {
                
            }

            @Override
            public void onFailure(String failureMessage) {
                
            }
        });

You will get the response in the following format.

class DrivingSummary {
    Double distance;
    int trips;
    Double duration;
    Double safetyScore;
    Double hardAcceleration;
    Double speeding;
    Double braking;
    Double laneChange;
    Double hardTurn;
    Double fatigue;
}

Working with vehicle tracking using MAC Address of the vehicle's bluetooth device

You might want to know whether the user is taking their trips in a particular vehicle (whether his own or the one assigned to him). Then you will need to pass the MAC address of the vehicle's bluetooth system to the Kruzr SDK. Then, whenever a trip is ongoing, the SDK will check whether the user is actually in that particular vehicle.

Saved MAC address of the vehicle will be cleared when deRegister(logout) method is called. You will have to save the mac address again.

Saving, Fetching and Clearing vehicle's details

You can save the devices received in the scan methods as the vehicle device through this method

Kruzr.getInstance()
     .saveVehicleDevice(Context context,NearByDevices nearByDevice);

You can get the saved details of the vehicle through this method.

Kruzr.getInstance()
     .getVehicleDevice(Context context);

You can clear the saved details of vehicle through this method

Kruzr.getInstance()
     .clearVehicleDevice(Context context);

Saving, Fetching and Clearing vehicle's MAC address

You can save a MAC address as the MAC address of vehicle through this method

Kruzr.getInstance()
     .saveMacAddressOfVehicle(Context context,String macAddress);

You can get the saved mac address (in String format) of the vehicle through this method.

Kruzr.getInstance()
     .getMacAddressOfVehicle(Context context);

You can clear the saved mac address of vehicle through this method

Kruzr.getInstance()
     .clearMacAddressVehicle(Context context);

Getting Paired Device List

You can call getPairedDevices method to receive a set of BluetoothDevice that the user has previously paired with. You can find more documentation about individual callback methods in the below code sample.

Some Bluetooth devices, particularly low-energy (BLE) devices, may not advertise their name in their scan response. This means that the device's name is not available to discoverable apps.

Kruzr.getInstance().getPairedDevices(this, new PairedDevicesCallbackInterface() {
            @Override
            public void deviceNotSupported() {
                // Bluetooth device is either missing or not working. No further operations can be done related to bluetooth.

            }

            @Override
            public void devicesFound(@NonNull Set<BluetoothDevice> setOfDevices) {
                for(BluetoothDevice bluetoothDevice : setOfDevices){
                    // bluetoothDevice.getName() and bluetoothDevice.getBondState() might return null for BLE devices.
                }
            }

            @Override
            public void requestUserToSwitchOnBluetooth() {
                // Device Bluetooth is turned off. You can notify the user to turn it on.
            }

            @Override
            public void permissionsNotGranted(@Nullable List<String> listOfMissingPermissions) {
                for(String missingPermission:listOfMissingPermissions){
                    // Handle missing permissions        
                }
            }
        });

Scanning for Nearby Bluetooth Devices

You can call this method to get nearby devices. Once the scanning starts onScanningStarted will be called followed by multiple callbacks of deviceFound on every new device discovery. Once the scanning ends, you will receive a callback in onScanningFinished. Usually the scanning stays active for 12 seconds as per default android rules.

Some Bluetooth devices, particularly low-energy (BLE) devices, may not advertise their name in their scan response. This means that the device's name is not available to discoverable apps.

Kruzr.getInstance().scanNearbyDevices(this, new BluetoothCallbackInterface() {
            @Override
            public void onScanningStarted() {
                // Called when scanning starts

            }

            @Override
            public void onScanningFinished() {
                // Called when scanning finished

            }

            @Override
            public void deviceFound(@Nullable BluetoothDevice bluetoothDevice) {
                // bluetoothDevice.getName() and bluetoothDevice.getBondState() might return null for BLE devices.

            }

            @Override
            public void deviceNotSupported() {
                // Bluetooth device is either missing or not working. No further operations can be done related to bluetooth.

            }

            @Override
            public void requestUserToSwitchOnBluetooth() {
                // Device Bluetooth is turned off. You can notify the user to turn it on.
            }

            @Override
            public void permissionsNotGranted(@Nullable List<String> listOfMissingPermissions) {
                for(String missingPermission:listOfMissingPermissions){
                    // Handle missing permissions
                }
            }
        });

Last updated

Was this helpful?