How to Invoke the Device Data Collector into Mobile Apps using the Native Android SDK

Use this guide for step two of a Native Android Application implementation of the Kount SDK. This guide provides instructions to add the SDK into the application and have it collect information about the device. You must send a sessionID back to your servers in order to use it to make Kount API calls related to this device/transaction.

Implementation Instructions

  1. To enable INTERNET access so the collector can transmit information back to Kount and Location Collection support to detect devices in suspicious locations, add the following permissions to your application’s XML under the <manifest> tag:
    <manifest>
    ....
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    </manifest>
  2. Enable Analytics Collection support. There are two methods to enable analytics support:
    1. For customers who do not use a custom application class.
      Enable Analytics Collection support by adding the following code to your application’s AndroidManifest.xml under the <application> tag. Refer to the code example below:
            <application
               android:name="com.kount.api.analytics.KountAnalyticsApplication"
               ...>
               ...
            </application>
            
    2. For customers who use a custom application class.
      Enable Analytics Collection support by adding Application.ActivityLifecycleCallbacks to your application class. Refer to the code example below:
      Application.ActivityLifecycleCallbacks
      import com.kount.api.analytics.AnalyticsApplication
      import com.kount.api.analytics.enums.EventEnums
      
      class CustomerApplication extends Application implements Application.ActivityLifecycleCallbacks {
      
        @Override
        public void onCreate() {
            AnalyticsApplication.init();
            registerActivityLifecycleCallbacks(this);
            super.onCreate();
        }
        
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
        }
        
        @Override
        public void onActivityStarted(Activity activity) {
            AnalyticsApplication.registerKountEvents(EventEnums.EVENT_STARTED, activity);
        }
        
        @Override
        public void onActivityResumed(Activity activity) {
            AnalyticsApplication.registerKountEvents(EventEnums.EVENT_RESUMED, activity);
        }
        
        @Override
        public void onActivityPaused(Activity activity) {
            AnalyticsApplication.registerKountEvents(EventEnums.EVENT_PAUSED, activity);
        }
        
        @Override
        public void onActivityStopped(Activity activity) {
            AnalyticsApplication.registerKountEvents(EventEnums.EVENT_STOPPED, activity);
        }
        
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
        }
        
        @Override
        public void onActivityDestroyed(Activity activity) {
        }
      }
  3. In the main activity of your application, you must initialize the collector and assign the <MERCHANT_ID> you received from Kount.
    Optionally, you can provide a sessionID if you need to generate your own; if not, the SDK generates one for you. You must send this sessionID back to your servers in order to make calls to the Kount API.
  4. Add the following initialization in your MainActivity:
    Initialization for MainActivity
            import com.kount.api.analytics.AnalyticsCollector;
            
            public class MainActity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
              final String deviceSessionID="";
              final String KEY_UUID="UUID";
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  ...
                  
                  AnalyticsCollector.setMerchantId(<MERCHANT_ID>);
                  
                  //This turns the alpha collections on(true)/off(false). It defaults to true
                  AnalyticsCollector.collectAnalytics(true);
                  
                  //For production need to add AnalyticsCollector.ENVIRONMENT_PRODUCTION
                  AnalyticsCollector.setEnvironment(AnalyticsCollector.ENVIRONMENT_TEST);
                  
                  if (savedInstanceState == null) {
                      /** If you want to pass in a self generated sessionID(or one given  to you by your servers) you can set it here instead of generating a UUID using the code below.  Make sure you set session ID only one time in a user session by saving it in the savedInstanceState.  An example to create a sessionID is below.**/
                      deviceSessionID = UUID.randomUUID().toString().replace('-','');
                      AnalyticsCollector.setSessionId(deviceSessionID);
                  } else {
                      deviceSessionID = savedInstanceState.getString(KEY_UUID)!!
                      AnalyticsCollector.setSessionId(deviceSessionID)
                  }
                  
                  //Request location permission for Android 6.0 & above
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    Utils.requestLocationPermission(this); //step:4
                  } else {
                      AnalyticsCollector.collectDeviceDataForSession(this);
              }    
                  
              @Override
              protected void onSaveInstanceState(@NonNull Bundle outState) {
                    super.onSaveInstanceState(outState);
                    outState.putString(KEY_UUID, deviceSessionID);
                }
                  
            }
            
  5. Your MainActivity should implement ActivityCompat.OnRequestPermissionsResultCallback and Override method onRequestPermissionsResult(requestCode, permissions, grantResults) as below:
         
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
      if (requestCode == AnalyticsCollector.REQUEST_PERMISSION_LOCATION) {
        //this block executes when a user grant/deny the permission
        AnalyticsCollector.collectDeviceDataForSession(this,(sessionId)-
        {
            //success block
            Log.d("TAG", "Client success completed with sessionId "+sessionId);
            Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
            return null;
        },(sessionId, error)-
        {
            //error block
            Log.d("TAG", "client failed with sessionId $error, $sessionId");
            Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
            return null;
        });
      }
      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
        
  6. To support Location Collection in Android API 23 and above, add the following permissions to your main activity, onCreate method:
       
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
          ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
      } else {
          ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
      }
    } else {
      //This block executes when permission is already granted.
          
      AnalyticsCollector.collectDeviceDataForSession(this,(sessionId)- {
          //success block
          Log.d("TAG", "Client success completed with sessionId "+sessionId);
          Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
          return null;
      },(sessionId, error)-
      {
          //error block
          Log.d("TAG", "client failed with sessionId $error, $sessionId");
          Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
          return null;
      });
    }
        
  7. Almost all Kount API calls require your Kount assigned merchantID and a sessionID. You must send the sessionID created earlier back to your servers. This can be done at any time prior to the Kount API calls being made (from your servers to ours). For example, if you are using Kount Control and plan to evaluate logins, you could include the sessionID along with the users login credentials to your servers. This sessionID is accessible as a global function.
        final String sessionId = AnalyticsCollector.getSessionId();
        // TODO add sessionId in posting to server here
        
  8. Build and run.
    Note: Compilation Problems? If android:allowbackup attribute is false in your <application> tag, add tools:replace="android:allowBackup" to your application tag.

Optional Additions

Changing your sessionID

If you need to change your sessionID for any reason (like a user logs out and then tries to login as someone else) you can set a new sessionID:

     
    // OPTIONAL SESSION_ID SECTION
    final String deviceSessionID = UUID.randomUUID().toString();.replace('-','')
    AnalyticsCollector.setSessionId(deviceSessionID);
    // END OPTIONAL SESSION_ID SECTION

Login session tracking

If you are using the Analytics collector and tracking login events, you can pass the value after a login event completes. To track login session data, add the following after the login attempt has completed:

Successful logins: AnalyticsCollector.trackLoginEvent(true);

Unsuccessful logins: AnalyticsCollector.trackLoginEvent(false);

Standard device data collection process

Calling AnalyticsCollector.collectDeviceDataForSession(this); starts the standard DDC collection. Device data collection happens once in a user session. When DDC completes its collection, data is sent to the server.

Android devices from version six onwards have a runtime permission feature where the application user can allow/deny location access permission. In order to make the SDK collect location data in the first user session, call the above method once the process of requesting runtime permissions is done.

You can refer to steps 4 and 5 for the sample code.

Device Data Collection Status Tracking

If you are using the Analytics collector and want to know the status of the Device data collection, you can use the below method. Whenever you call this method, it will return the collection status of the DDC collector at that point of time. Use this line of code in those methods which executes After onCreate() method because we are calling the Collector in onCreate() (refer to steps 3, 4, and 5). You can also use this in Activities/Fragments which executes after your main activity.

DeviceDataCollector.CollectionStatus status = AnalyticsCollector.getCollectionStatus();
        //if status is FAILED call status.getError() to get Error details.
        if (status == DeviceDataCollector.CollectionStatus.FAILED) {
             status.getError()
        }

This method returns one of the values below:

  1. INPROGRESS: When collection is started and collectors are running in the background for device information collection.
  2. FAILED: When Datacollector fails to capture/send the device data. Possible causes for this failure are No network, Invalid Merchant ID, Invalid Session ID, and Runtime failures.
  3. COMPLETED: When DataCollector completes its collection and send data to Server.
  4. NOT_STARTED: When DataCollector SDK is not initialized.(calling AnalyticsCollector.collectDeviceDataForThisSession(this) will do the initialization, only one time in application session)
Was this article helpful?
1 out of 1 found this helpful