# Android Integration

Integration Sample Code

You can refer to the integration sample code here https://github.com/finogeeks/mop-android-demo (opens new window)

# 1. Obtain SDK Key, SDK Secret, and SDK Fingerprint

Using the SDK requires applying for an SDK Key, SDK Secret, and SDK Fingerprint. The SDK can only be initialized successfully and function normally when the correct SDK Key, SDK Secret, and SDK Fingerprint are configured during initialization.

# 1.1 Create an Application

Registered users can add a partner application on the application management page.

# 1.2 Export SDK Key and SDK Secret

Click Export to view the SDK Key and SDK Secret.

  • SDK Key: This is the credential that allows the partner application to use the Mini-Program SDK. If the SDK Key verification fails, all APIs of the SDK will be unavailable.
  • SDK Secret: This is the security certificate for accessing the service. Do not share it with third parties.

# 1.3 Export SDK Fingerprint

Click the left menu item 【SDK Management】, add an SDK vendor, upload the iOS and Android SDKs. After the review is passed, you can export the SDK Fingerprint.

# 2. Import the SDK

# 2.1 Configuration Required in the Project's build.gradle

Add the maven repository address in the project's build.gradle:

maven {
    url "https://gradle.finogeeks.club/repository/applet/"
    credentials {
		username "applet"
		password "123321"
	}
}

Since part of the SDK code is written in Kotlin, the Kotlin gradle plugin needs to be added to the project's build.gradle:

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"

The complete configuration of the project's build.gradle is as follows:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.5.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://gradle.finogeeks.club/repository/applet/"
            credentials {
                username "applet"
                password "123321"
            }
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

# 2.2 Depend on the SDK in gradle

Add the dependency for finapplet in the dependencies section of the gradle file:

implementation 'com.finogeeks.lib:finapplet:x.y.z' //x.y.z must be replaced with the specific version number

The dynamic libraries in the SDK are obfuscated. Obfuscated dynamic libraries cannot be compressed during compilation and packaging, otherwise an error will occur when loading. Therefore, add the doNotStrip configuration in the build.gradle of the App module:

packagingOptions {
    // libsdkcore.so and libyuvutil.so are obfuscated and cannot be compressed, otherwise an error will occur when loading the dynamic library
    doNotStrip "*/x86/libsdkcore.so"
    doNotStrip "*/x86_64/libsdkcore.so"
    doNotStrip "*/armeabi/libsdkcore.so"
    doNotStrip "*/armeabi-v7a/libsdkcore.so"
    doNotStrip "*/arm64-v8a/libsdkcore.so"

    doNotStrip "*/x86/libfin-yuvutil.so"
  	doNotStrip "*/x86_64/libfin-yuvutil.so"
  	doNotStrip "*/armeabi/libfin-yuvutil.so"
  	doNotStrip "*/armeabi-v7a/libfin-yuvutil.so"
  	doNotStrip "*/arm64-v8a/libfin-yuvutil.so"
}

The complete configuration is as follows:

apply plugin: 'com.android.application'

android {
    buildToolsVersion '28.0.3'
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.finogeeks.finappletdemo"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        // libsdkcore.so is obfuscated and cannot be compressed, otherwise an error will occur when loading the dynamic library
        doNotStrip "*/x86/libsdkcore.so"
        doNotStrip "*/x86_64/libsdkcore.so"
        doNotStrip "*/armeabi/libsdkcore.so"
        doNotStrip "*/armeabi-v7a/libsdkcore.so"
        doNotStrip "*/arm64-v8a/libsdkcore.so"
      
        doNotStrip "*/x86/libyuvutil.so"
    		doNotStrip "*/x86_64/libyuvutil.so"
    		doNotStrip "*/armeabi/libyuvutil.so"
    		doNotStrip "*/armeabi-v7a/libyuvutil.so"
    		doNotStrip "*/arm64-v8a/libyuvutil.so"
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.finogeeks.lib:finapplet:x.y.z' //x.y.z must be replaced with the specific version number
}

# 2.3 Configure Obfuscation Rules

After integrating the SDK, to prevent certain code in the SDK that should not be obfuscated from being obfuscated, add the following configuration to the project's obfuscation rule configuration file:

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

# 3. SDK Initialization

We strongly recommend initializing the SDK in the Application. The parameters required for initializing the SDK are as follows:

# 3.1 Configuration Information for the Mini-Program Framework

Before version 2.13.102, the SDK only supported configuring one server information, meaning it could only open Mini-Programs from a single environment. The configuration parameters are as follows:

FinAppConfig config = new FinAppConfig.Builder()
        .setSdkKey("SDK Key information")   // SDK Key
        .setSdkSecret("SDK Secret information")   // SDK Secret
        .setSdkFingerprint("SDK Fingerprint")   // SDK Fingerprint
        .setApiUrl("Server address")   // Server address
        .setApiPrefix("/api/v1/mop/")   // Server interface request route prefix
        .setEncryptionType("Encryption type")   // Encryption type, SM for National Secret, MD5 for md5
        .build();

Starting from version 2.13.102, configuring multiple server information is supported, allowing Mini-Programs from different environments to be opened simultaneously. The configuration parameters are as follows:

// Collection of server information
List<FinStoreConfig> storeConfigs = new ArrayList<>();

// Information for Server 1
FinStoreConfig storeConfig1 = new FinStoreConfig(
        "SDK Key information",   // SDK Key
        "SDK Secret information",   // SDK Secret
        "Server 1 address",   // Server address
        "Server 1 data reporting server address",   // Data reporting server address
        "/api/v1/mop/",   // Server interface request route prefix
        "SDK Fingerprint",   // SDK Fingerprint
        "Encryption type"   // Encryption type, SM for National Secret, MD5 for md5
);
storeConfigs.add(storeConfig1);

// Information for Server 2
FinStoreConfig storeConfig2 = new FinStoreConfig(
        "SDK Key information",   // SDK Key
        "SDK Secret information",   // SDK Secret
        "Server 2 address",   // Server address
        "Server 2 data reporting server address",   // Data reporting server address
        "/api/v1/mop/",   // Server interface request route prefix
        "SDK Fingerprint",   // SDK Fingerprint
        "Encryption type"   // Encryption type, SM for National Secret, MD5 for md5
);
storeConfigs.add(storeConfig2);

FinAppConfig config = new FinAppConfig.Builder()
        .setFinStoreConfigs(storeConfigs) // Collection of server information
        .build();

# 3.2 Set the SDK Initialization Status Callback

Implement the FinCallback interface to listen for the SDK initialization status:

// SDK initialization result callback, used to receive the SDK initialization status
FinCallback<Object> callback = new FinCallback<Object>() {
    @Override
    public void onSuccess(Object result) {
        // SDK initialization successful
    }

    @Override
    public void onError(int code, String error) {
        // SDK initialization failed
        Toast.makeText(AppletApplication.this, "SDK initialization failed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgress(int status, String error) {

    }
};

# 3.3 Initialize the SDK

Call the initialization interface to initialize the SDK:

FinAppClient.INSTANCE.init(this, config, callback);

# 3.4 SDK Initialization Multi-Process Handling

The SDK uses a multi-process mechanism, where each Mini-Program runs in an independent process, meaning one Mini-Program corresponds to one process. When initializing the SDK, it is particularly important to note: the Mini-Program process does not need to perform any initialization operations when created, not even the initialization of the Mini-Program SDK.

For example: if the application uses some third-party libraries that need to be initialized when the application starts, then when performing initialization in the Application, these third-party libraries only need to be initialized if the current process is the Host-App process. The Mini-Program process does not need to initialize these libraries.

Therefore, before initializing the SDK, you must determine which process the current process is. If it is a Mini-Program process, do not perform any operations:

if (FinAppClient.INSTANCE.isFinAppProcess(this)) {
    return;
}

The above is the entire process for initializing the SDK. The complete code is as follows:

package com.example.finogeeks.appletdemo;

import android.os.Process;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.finogeeks.appletdemo.api.ApiOpenPage;
import com.example.finogeeks.appletdemo.api.ApiOpenPageForResult;
import com.example.finogeeks.appletdemo.api.DrawModule;
import com.example.finogeeks.appletdemo.util.ProcessUtilKt;
import com.finogeeks.lib.applet.client.FinAppClient;
import com.finogeeks.lib.applet.client.FinAppConfig;
import com.finogeeks.lib.applet.interfaces.FinCallback;

/**
 * The application's {@link android.app.Application}
 */
public class AppletApplication extends MultiDexApplication {
    
    @Override
    public void onCreate() {
        super.onCreate();

        if (FinAppClient.INSTANCE.isFinAppProcess(this)) {
            // Mini-Program process does not perform any initialization operations
            return;
        }
        
        // Collection of server information
		List<FinStoreConfig> storeConfigs = new ArrayList<>();

		// Information for Server 1
		FinStoreConfig storeConfig1 = new FinStoreConfig(
        		"SDK Key information",   // SDK Key
        		"SDK Secret information",   // SDK Secret
        		"Server 1 address",   // Server address
        		"Server 1 data reporting server address",   // Data reporting server address
        		"/api/v1/mop/",   // Server interface request route prefix
        		"SDK Fingerprint",   // SDK Fingerprint
        		"Encryption type"   // Encryption type, SM for National Secret, MD5 for md5
		);
		storeConfigs.add(storeConfig1);

		// Information for Server 2
		FinStoreConfig storeConfig2 = new FinStoreConfig(
        		"SDK Key information",   // SDK Key
        		"SDK Secret information",   // SDK Secret
        		"Server 2 address",   // Server address
        		"Server 2 data reporting server address",   // Data reporting server address
        		"/api/v1/mop/",   // Server interface request route prefix
        		"SDK Fingerprint",   // SDK Fingerprint
        		"Encryption type"   // Encryption type, SM for National Secret, MD5 for md5
		);
		storeConfigs.add(storeConfig2);

		FinAppConfig config = new FinAppConfig.Builder()
        		.setFinStoreConfigs(storeConfigs) // Collection of server information
        		.build();

        FinAppClient.INSTANCE.init(this, config, new FinCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
            }

            @Override
            public void onError(int code, String error) {
                Toast.makeText(AppletApplication.this, "SDK initialization failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProgress(int status, String error) {

            }
        });
    }
}

# 4. SDK Usage Examples

# 4.1 Start a Mini-Program

After a Mini-Program is published on the platform, we can open it by calling the Mini-Program startup interface in the SDK. The code to start a Mini-Program is as follows:

FinAppClient.INSTANCE.getAppletApiManager().startApplet(this, "5e0dc1f574193e00010d73c1");

If startup parameters need to be passed when starting the Mini-Program, you can call the interface that supports passing startup parameters, as shown below:

Map<String, String> params = new HashMap<>();
// path is the Mini-Program page path
params.put("path", "/pages/index/index");
// query is the startup parameter, in the form of "key1=value1&key2=value2 ..."
params.put("query", "aaa=test&bbb=123");
FinAppClient.INSTANCE.getAppletApiManager().startApplet(this, "5e0dc1f574193e00010d73c1", params);

# 4.2 Custom Mini-Program API

Implementing a custom Mini-Program API requires creating a class that inherits from AbsApi and overriding the parent class methods (primarily the apis() method and the invoke() method). The following example demonstrates how to implement and register a custom Mini-Program API by opening a native page from within a Mini-Program.

First, create the ApiOpenPage class, inheriting from AbsApi;

Then, override the apis() method in ApiOpenPage to return the names of all callable APIs. You can add multiple API names in the array returned by apis(); the current example only adds one, openPage;

Finally, override the invoke() method in ApiOpenPage to implement the corresponding logic. The current example implements a simple page navigation: if the openPage API is called within the Mini-Program, it will start an Activity on the native side.

package com.example.finogeeks.appletdemo.api;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.example.finogeeks.appletdemo.SecondActivity;
import com.finogeeks.lib.applet.api.AbsApi;
import com.finogeeks.lib.applet.interfaces.ICallback;

import org.json.JSONObject;

/**
 * Custom Mini-Program API, implementing simple page navigation functionality
 */
public class ApiOpenPage extends AbsApi {

    private Context mContext;

    public ApiOpenPage(Context context) {
        mContext = context;
    }

    /**
     * Returns an array of callable API names
     *
     * @return Array of callable API names
     */
    @Override
    public String[] apis() {
        return new String[]{"openPage"};
    }

    /**
     * This method is triggered when the corresponding API call is received. Implement the API's business logic here.
     *
     * @param event    Event name, i.e., the API name
     * @param param    Event parameters
     * @param callback Callback interface, used to callback the result to the Mini-Program after the business logic is executed
     */
    @Override
    public void invoke(String event, JSONObject param, ICallback callback) {
        if ("openPage".equals(event)) {
            String url = param.optString("url");
            if (!TextUtils.isEmpty(url)) {
                Intent intent = new Intent();
                intent.setClass(mContext, SecondActivity.class);
                mContext.startActivity(intent);
                callback.onSuccess(null);
            } else {
                callback.onFail();
            }
        }
    }
}

After implementing the custom Mini-Program API, two more steps are required to call the API from the Mini-Program:

  1. Register the custom Mini-Program API with the SDK. This is done by calling the registerApi method of the IExtensionApiManager interface:
FinAppClient.INSTANCE.getExtensionApiManager().registerApi(new ApiOpenPage(context));
  1. Add the custom API configuration in the Mini-Program project. Create a FinClipConf.js file in the root directory of the Mini-Program project and configure the corresponding custom API in FinClipConf.js as follows:
module.exports = {
  	extApi:[
    	{
      		name: 'openPage', // Extension API name
      		params: { // Extension API parameters, only necessary parameters need to be listed
        		url: ''
      		}
    	}
  	]
}

For more custom API configuration information on the Mini-Program side, please refer to ft.loadExtApi

# 4.3 Interaction Between Native and Mini-Program Web Pages

When a Mini-Program loads a web page, if the web page needs to call native functions, the native code must be registered inside the SDK as a custom JSSDK API.

The implementation method for a custom JSSDK API is the same as for a custom Mini-Program API, i.e., inherit AbsApi and override the parent class methods. The difference is that when registering the API, you call the registerApi method of IExtensionWebApiManager, not the method in IExtensionApiManager:

FinAppClient.INSTANCE.getExtensionWebApiManager().registerApi(new WebApi(context));

At the same time, the SDK also supports native code calling JavaScript code in the web page. The calling method is as follows:

FinAppClient.INSTANCE.getAppletApiManager().callJS("appId", "funcName", "funParams", 1)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
                result -> Toast.makeText(context, "callJS successfully : " + result, Toast.LENGTH_SHORT).show(),
                throwable -> Toast.makeText(context, "callJS failed : " + throwable.getLocalizedMessage(), Toast.LENGTH_SHORT).show()
        );

# 5. About the Extension SDK

The above content revolves around the core SDK, finapplet. In addition to the core SDK, we also provide an Extension SDK. The Extension SDK is a library that depends on the core SDK and provides various Mini-Program APIs not available in the core SDK.

The reason for providing the Extension SDK is to ensure that the core SDK remains lightweight while also ensuring that the Mini-Program APIs are sufficiently rich. The core SDK is responsible for establishing the basic framework for running Mini-Programs and providing a small set of essential APIs. In terms of permissions, it only retains basic permissions such as storage, camera, and location, and its size is just over 1MB. The Extension SDK exists as a supplement to the core SDK, and its APIs will continue to be enriched and improved.

If you wish to use the APIs in the Extension SDK, simply depend on the Extension SDK library in gradle:

implementation 'com.finogeeks.mop:plugins:x.y.z' //x.y.z must be replaced with the specific version number
© FinClip with ❤ , Since 2017