Android compiles the so file that holds the secret key

To be safe, we sometimes put the secret key in a so file. How is a so file compiled and used? Refer to the link: www.jianshu.com/p/faa3eebbd…

1. Create a Java file.

public class JNIUtil {

    static {
        System.loadLibrary("web-lib");
    }

    public static native String initData();
}

Copy the code

2. Generate jNI from a Java file

  1. In the code directorymainCreate in directoryjniThe directory where the
  2. Automatically generated by creating a Java file.hfile

Setting->Tools->External Tools->External Tools->External Tools->External Tools

Name: The NDK - build the Program: $JDKPath$\bin\javah.exe Argument:-classpath . -jni -d $ModuleFileDir$/src/main/jni $FileClass$ Working directory:$ModuleFileDir$\src\main\JavaCopy the code

Note: Program is the path of Javah, need to be adjusted according to the JDK path, other parameters can be consistent with the appeal.

  1. Place the cursor on the Java file created in the first step and right click on it ->External Tools->ndk-build (this will generate the corresponding file in JNI.hFile)

3. Create aAndroid.mkApplication.mkC file

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := web-lib

LOCAL_SRC_FILES := jni.c

include $(BUILD_SHARED_LIBRARY)

Copy the code

Application.mk

APP_ABI:=all

Copy the code

jni.c

#include <stdio.h>

#include <com_bupin_jni_JNIUtil.h>


JNIEXPORT jstring JNICALL
Java_com_bupin_jni_JNIUtil_initData(JNIEnv *env, jobject jobj){
  char *cstr = "xxx";
  jstring jstr = (*env)->NewStringUTF(env, cstr);
return jstr;
}


Copy the code

4. Add a build file

Inside the Android TAB in app/build.gradle

Sourcesets. main {jni.srcdirs = [] jnilibs. srcDirs = [' SRC /main/jniLibs']} task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {commandLine "F:\\AndroidStudioSdk\\ NDK \\20.1.5948944\\ndk-build.cmd", // Configure the NDK path 'NDK_PROJECT_PATH=build/intermediates/ NDK ', // the default NDK file to generate so 'NDK_LIBS_OUT= SRC /main/jniLibs', // Configure the location of 'APP_BUILD_SCRIPT= SRC /main/jni/ android.mk 'where we want to generate the so file,// specify the project as this mk 'NDK_APPLOCATION_MK = SRC/main/jni/Application. The mk' / / specified project.} the tasks in the form of the mk withType (JavaCompile) {/ / using ndkBuild compileTask -> compileTask.dependsOn ndkBuild }Copy the code

5. Compile to so

Click Build -> Make Project to generate the so file in the appropriate directory.

At this point you can use the SO file.

Just use it


JNIUtil.initData()

Copy the code