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

If you have not completed the initial integration step, refer to How to Integrate the Device Data Collector into Mobile Apps using Android Gradle or How to Integrate the Device Data Collector into Android Applications using the Library JAR depending on your integration type.

This guide is for step two of a Kotlin Android Application implementation of the SDK. This guide provides instructions on how to add the SDK into the application and have it collect information about the device.

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>

    Note

    While preferred, not all apps are approved in the app store to use the ACCESS_FINE_LOCATION. If your app has been rejected for having this permission, replace ACCESS_FINE_LOCATION (uses GPS) with ACCESS_COARSE_LOCATION (uses cellular triangulation).

  2. There are two ways to enable Analytics support:

    • No custom application class

      Enable support by adding the following code to your application’s AndroidManifest.xml under the <application> tag.

            <application
              android:name="com.kount.api.analytics.KountAnalyticsApplication"
              ...>
              ...
            </application>
            
    • Custom application class:

      Enable support by adding Application.ActivityLifecycleCallbacks to your application class.

                import com.kount.api.analytics.AnalyticsApplication
                import com.kount.api.analytics.enums.EventEnums
                
                class CustomerApplication :Application(),Application.ActivityLifecycleCallbacks {
                  override fun onCreate() {
                    AnalyticsApplication.init()
                    registerActivityLifecycleCallbacks(this)
                    super.onCreate()
                  }
                  
                  override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                  }
                  
                  override fun onActivityStarted(activity: Activity) { 
                    AnalyticsApplication.registerKountEvents(EventEnums.EVENT_STARTED, activity)
                  }
                  
                  override fun onActivityResumed(activity: Activity) {
                    AnalyticsApplication.registerKountEvents(EventEnums.EVENT_RESUMED, activity)
                  }
                  
                  override fun onActivityPaused(activity: Activity) {
                    AnalyticsApplication.registerKountEvents(EventEnums.EVENT_PAUSED, activity)
                  }
                  
                  override fun onActivityStopped(activity: Activity) {
                    AnalyticsApplication.registerKountEvents(EventEnums.EVENT_STOPPED, activity)
                  }
                  override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                  }
                  
                  override fun onActivityDestroyed(activity: Activity) {
                  }
                }
                
  3. In the main activity of your application, initialize the Device Data Collector and assign the <MERCHANT_ID> you received. Optionally, you can provide a sessionID if you need to generate your own (if not, the SDK will generate one for you). You must send this sessionID back to your servers in order to make calls to the API. Add the following code in your MainActivity:

    AnalyticsCollector.collectDeviceDataForSession(this, { sessionID - //success block}, { sessionID, error - //error block}) 

    This starts standard device data collection. You can add the functionality for onSuccess and onFailure in the success and error blocks. For example, you can get the collection status by calling AnalyticsCollector.getCollectionStatus(). Make sure to call this method after the user selects allow/deny in the location permission dialog because to capture location data in the first session, location access must be given.

    This method is called at three places in the below sample code to fulfill the requirement above.

    AnalyticsCollector.collectDeviceDataForSession

    import com.kount.api.analytics.AnalyticsCollector
    …
            
    class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback {
        private var deviceSessionID= ""
        private var KEY_UUID= "UUID"
                
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
                        
            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)// refer step 4
            } else {
              AnalyticsCollector.collectDeviceDataForSession(this, { sessionId ->
                    Log.d("TAG", "success completed with sessionId $sessionId")
                    Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
                }, { sessionId, error ->
                    Log.d("TAG", " failed with sessionId $error, $sessionId")
                    Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
                })
            }
                      
            ...
            }
            // To maintain same sessionId even after screen rotation
            override fun onSaveInstanceState(outState: Bundle) {
            super.onSaveInstanceState(outState)
            outState.putString(KEY_UUID, deviceSessionID)
        }
                        
    }
            
            
  4. Your MainActivity should implement ActivityCompat.OnRequestPermissionsResultCallback and override method onRequestPermissionsResult(requestCode, permissions, grantResults) as provided below:

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
      if (requestCode == AnalyticsCollector.REQUEST_PERMISSION_LOCATION) {      
         AnalyticsCollector.collectDeviceDataForSession(this, { sessionId ->
           Log.d("TAG", "success completed with sessionId $sessionId")
           Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
         }, { sessionId, error ->
           Log.d("TAG", " failed with sessionId $error, $sessionId")
           Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
         })
      }
      super.onRequestPermissionsResult(requestCode, permissions, grantResults)
      }
        
        
  5. To support location collection in Android API 23 and later, add the following code 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, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), AnalyticsCollector.REQUEST_PERMISSION_LOCATION)
      } else {
         ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), AnalyticsCollector.REQUEST_PERMISSION_LOCATION)
      }
    } else {
      AnalyticsCollector.collectDeviceDataForSession(this, { sessionId ->
         Log.d("TAG", "success completed with sessionId $sessionId")
         Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
      }, { sessionId, error ->
         Log.d("TAG", " failed with sessionId $error, $sessionId")
         Log.d("TAG", "DDC STATUS is :" + AnalyticsCollector.getCollectionStatus()?.name)
      })
    }
        
  6. Almost all API calls require your assigned merchantID and a sessionID. Send the sessionID created earlier back to your servers. This can be done at any time prior to the API calls being made (from your servers to ours). For example, if you are using our services and plan to evaluate logins, you could include the sessionID along with the user's login credentials to your servers. This sessionID is accessible as a global variable.

       
        …
        val sessionId = AnalyticsCollector.getSessionId()
        // TODO add sessionId in posting to server here
        …
        
  7. 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.

Was this article helpful?
0 out of 0 found this helpful