Android Guide

Learn about OkHi's integration for verifying addresses.

1. Set up OkHi (Client-side)

Check out our full OkVerify integration example

Androidx

Make sure AndroidX is enabled in your project by modifying android/gradle.properties and adding 2 lines:

android.useAndroidX=true
android.enableJetifier=true

Add the OkHi Maven repository to your settings.gradle file

In your settings.gradle file, located at the root folder of your project. Add the new OkHi Maven Repository under the dependencyResolutionManagement section.

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url "https://repo.okhi.io/artifactory/maven" }
        ...
    }
}

The OkHi libraries target Android devices >= SDK 21. Make sure you're targeting at least the same and set compileSdkVersion & targetSdkVersion to 33 by modifying your app/build.gradle file

android {
    compileSdkVersion 33
    targetSdkVersion 33
    minSdkVersion 21
    ...

Add the OkHi Core library dependencies

dependencies {
    implementation 'io.okhi.android:core:1.7.15'
    implementation 'io.okhi.android:okcollect:3.3.20'
    implementation 'io.okhi.android:okverify:1.9.31'
}

Check for the latest release on GitHub:

android-core

android-okcollect

android-okverify

Next, configure your Android apps as follows:

Open your AndroidManifest.xml located under android/app/src/main/AndroidManifest.xml and add:

  1. your credentials (obtain these by filling out this form) as shown below​.

  2. required permissions: ACCESS_FINE_LOCATION and ACCESS_BACKGROUND_LOCATION

<manifest ...>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    ...
    
    <application>
        <meta-data android:name="io.okhi.core.branch_id" android:value="<my_branch_id>" />
        <meta-data android:name="io.okhi.core.client_key" android:value="<my_client_key>" />
        <meta-data android:name="io.okhi.core.environment" android:value="prod" />
        <meta-data android:name="io.okhi.core.platform" android:value="android" />
    ...
    </application>

</manifest>

If you're targeting Android versions >= 8 and you're using the OkVerify library you need to make sure your users select "Allow always" when granting permissions otherwise the verification process won't work.

Building with pro-guard enabled

If you have minifyEnabled set to true in your build.gradle file located android/app/build.gradle, you'll need to modify your proguard-rules.pro file, located android/app/proguard-rules.proas shown below to include classes required by the library to run.

-dontwarn sun.reflect.**
-dontwarn java.beans.**
-dontwarn sun.nio.ch.**
-dontwarn sun.misc.**

-keep class com.esotericsoftware.** {*;}

-keep class java.beans.** { *; }
-keep class sun.reflect.** { *; }
-keep class sun.nio.ch.** { *; }

-keep class com.snappydb.** { *; }
-dontwarn com.snappydb.**

# If you don't use OkHttp as a dep and the following

-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okhttp3.internal.platform.ConscryptPlatform
-dontwarn org.conscrypt.ConscryptHostnameVerifier

2. Create and verify an address (Client-side)

Add a button to your UI that would enable the launching of OkHi address collection tool.

We recommend that you persist the verification state of the user in your app's local storage. This state can be used to ensure that a user may only verify a predefined number of addresses. Usually, one address is for most use cases.

Create an instance of the OkVerify class to be used later in your class.

Important: Make sure to invoke the static init method once on app start.

public class Sample extends AppCompatActivity {

    private OkHi okhi;
    private OkCollect okCollect;
    private OkVerify okVerify;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpOkHi();
        Button btn = findViewById(R.id.btnSubmit);
        btn.setOnClickListener(view -> handleButtonClick());
    }

    private void handleButtonClick() {
        OkHiUser user = new OkHiUser.Builder("+234xxxxx") // It is important to provide your actual phone number, as a message will be sent to this number
        .withFirstName("Gift")
        .withLastName("Moore")
        .withEmail("giftmoore@okhi.com") // it is important to use your actual email address, an email may be sent to the provided address
        .build();
        startAddressCreation(user);
    }

    private void startAddressCreation(OkHiUser user) {
        okhi.requestEnableVerificationServices(new OkHiRequestHandler<Boolean>() {
            @Override
            public void onResult(Boolean result) {
                if (result) {
                    okCollect.launch(user, OkCollectLaunchMode.CREATE, new OkCollectCallback<OkHiUser, OkHiLocation>() {
                        @Override
                        public void onSuccess(OkHiUser okHiUser, OkHiLocation location) {
                            startAddressVerification(okHiUser, location);
                        }
                        @Override
                        public void onClose() {
                            Toast.makeText(Sample.this, "User closed", Toast.LENGTH_LONG).show();
                        }
                        @Override
                        public void onError(OkHiException e) {
                            Toast.makeText(Sample.this, e.getCode() + ":" + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
            @Override
            public void onError(OkHiException e) {
                Toast.makeText(Sample.this, e.getCode() + ":" + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void startAddressVerification(OkHiUser user, OkHiLocation location) {
        okVerify.start(user, location, new OkVerifyCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(Sample.this, "Started verification for: " + result, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(OkHiException e) {
                Toast.makeText(Sample.this, e.getCode() + ":" + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void setUpOkHi() {

        final OkHiTheme theme = new OkHiTheme.Builder("#333333").setAppBarLogo("https://cdn.okhi.co/icon.png").setAppBarColor("#333333").build();
        final OkHiConfig config = new OkHiConfig.Builder().withStreetView().build();

        int importance = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? NotificationManager.IMPORTANCE_DEFAULT : 3;
        OkVerify.init(getApplicationContext(), new OkHiNotification(
                "Verifying your address",
                "We're currently verifying your address. This won't take long",
                "OkHi_Test",
                "OkHi Address Verification",
                "Alerts related to any address verification updates",
                importance,
                1, // notificationId
                2 // notification request code
        ));

        try {
            okhi = new OkHi(this);
            okCollect = new OkCollect.Builder(this).withTheme(theme).withConfig(config).build();
            okVerify = new OkVerify.Builder(this).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        okhi.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        okhi.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}

Test

If verification has started successfully:

  • A persistent notification should show, indicating that verification is ongoing

Common issues:

  • If background location permission is not granted, verification will not start

3. Add address endpoint (Server-side)

Here's a sample address payload that the client would get on successful address collection:

{
    "user": {
        "id": "B5QgvjE8WC",
        "phone": "+234xxxx",
        "firstName": "Gift",
        "lastName": "Moore"
    },
    "location": {
        "id": "8F0yPK1Zdj",
        "lat": 6.442849499999999,
        "lon": 3.424421,
        "plusCode": "6FR5CCVF+4Q",
        "propertyName": "10",
        "streetName": "Raymond Njoku Street",
        "title": "Raymond Njoku Street",
        "subtitle": "10",
        "url": "https://okhi.me/8F0yPK1Zdj",
        "streetViewPanoId": "ufxEWf-zpKLcTxIe04o6Bg",
        "streetViewPanoUrl": "https://maps.googleapis.com/maps/api/streetview?size=640x640&fov=45&location=6.44275037195316%2C3.424513218681455&heading=321.4785708568841&pitch=-9.5945875978788",
        "userId": "B5QgvjE8WC",
        "displayTitle": "10, Raymond Njoku Street",
        "country": "Nigeria",
        "state": "Lagos",
        "city": "Eti-Osa",
        "countryCode": "ng"
    }
}

Create a secure endpoint on your server that your app can use to pass address details to your server. Remember to handle corner cases such as, address updates, multiple addresses if your app supports it.

//Secure new address endpoint
app.post("/users/addresses", async (req) => {
  const { user, location } = req.body;
  const { id, firstName, lastName, phone } = user;
  const {
    id: locationId, displayTitle, title, subtitle, country, state, city, countryCode, lat, lon, plusCode, propertyName, streetName, url, streetViewPanoId, streetViewPanoUrl
  } = location;
  console.log(user, location);
  // Store the location.id. Used to match webhook updates
  return;
});

4. Handle verification events (Server-side)

OkHi sends verification status updates over a few days while verification is ongoing. Follow the webhook guide to set up a webhook to receive these verification status updates and run actions such as upgrading a user's KYC level.

5. Show verification status in app(Server- & Client-side)

Create a secure endpoint to enable your app to retrieve address details, including the verification status received from the webhook

// Secure address retrieval endpoint
app.get("/users/addresses", (req) => {
  // Get data from db. Example result:
  const dbResult = {
    "id": "8F0yPK1Zdj",
    "status": "verified",
    "displayTitle": "10, Raymond Njoku Street",
    "title": "Raymond Njoku Street",
    "subtitle": "10",
    "country": "Nigeria",
    "state": "Lagos",
    "city": "Eti-Osa",
    "countryCode": "ng",
  }
  return dbResult;
});

Show the resulting address details and status on the address page in your app.

6. Test the integration

7. Customise the integration

Create a location permissions primer (Required)

Create your custom location permissions primer to educate your user on the requirement for location permissions. Make sure to follow our design best practices to ensure you meet the Google Play store and AppStore requirements.

Customise OkCollect (optional)

Its possible to completely transform the default appearance of OkHiLocationManager to better match your brand by providing values to the theme prop

Its possible to completely transform the default apperance of OkHiLocationManager to better match your brand by providing values to the OkHiTheme.Builder

private void setUpOkHi() {

    final OkHiTheme theme = new OkHiTheme.Builder("#333333")
        .setAppBarLogo("https://cdn.okhi.co/icon.png")
        .setAppBarColor("#333333")
        .build();
    
    // ...Other setup details
    
    try {
        okhi = new OkHi(this);
        okCollect = new OkCollect.Builder(this)
            .withTheme(theme)
            .withConfig(config).build();
            
        okVerify = new OkVerify.Builder(this).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
}}

Customizing address type

You may turn off either of the OkHi address types. This is to allow your users to create either home or work addresses to better suit your use-case. By default, both address types are on.

OkHiConfig config = new OkHiConfig.Builder()
    .withStreetView()
    .withWorkAddressType(false)
    .withHomeAddressType(true)
    .build();

Customise notification icon & color

You can specify a custom default icon and a custom default color by adding these lines inside the application tag to set the custom default icon and custom color. You'll need to have already created the icon resource in your Android application. Icon assets can be created by following these steps

<application>
    <meta-data android:name="io.okhi.core.branch_id" android:value="<my_branch_id>" />
    <meta-data android:name="io.okhi.core.client_key" android:value="<my_client_key>" />
    <meta-data android:name="io.okhi.core.environment" android:value="prod" />
    <meta-data android:name="io.okhi.core.platform" android:value="android" />
    
    <!-- Set custom default icon for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_icon" android:resource="@drawable/ic_person_pin" />
    <!-- Set custom default icon color for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_color" android:resource="@color/colorAccent" />
    
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Important: Prepare for submission to the Google Play store

Submitting an app to the Google Play store that has background location permissions has a few extra requirements. Follow these guide to know what to expect and how to handle the extra requirements:

Publishing to Google Play store

Next steps

Review Full integration sample project

Review Android libraries documentation

Review OkHi integration best practices

Last updated