Android JNI Application With NDK (Java as well as in Kotlin)

We will Secure Our API keys using NDK. NDK Stand for Native Development Kit.

Note : Make Sure We have install NDK in Your Android SDK.


 Step 1: Create Jni Folder in Our Main Directory.


  • Change Android Directly to Project.
  • Create New Jni Directly Under APP > SRC Folder.


Step 2: Now Create 3 File Under Jni Directory 

  • Android.mk
  • Application.mk
  • api-keys.c

  • Create Android.mk file and Paste Below Code.
//Code

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := api-keys
LOCAL_SRC_FILES := api-keys.c
include $(BUILD_SHARED_LIBRARY)

  • Create Application.mk file and Paste Below Code.

APP_ABI := all

Now at the End ,Create api-keys.c file and Paste Below Code.

#include <jni.h>

//For first API key 
JNIEXPORT jstring JNICALL Java_com_d2dreamdevelopers_myapplication_APIKeyLibrary_getAPIKey(JNIEnv *env, jobject instance) { 
return (*env)-> NewStringUTF(env, "YOUR_AWESOME_API_GOES_HERE"); 
}

Step 3: Now Link Our C File to Gradle.


Right Click on api-keys.c File. And Click on Link C++ Project With Gradle.


In this Dialog, 
        Build System -> ndk-build
        Project Path -> Select Android.mk file of your Project.

In this Dialog Select ndk-build in Build System and Project Path Give Android.mk file.

Step 4 : Write getKeys() in Our MainActivity Class or Where we Need the Key.

For Kotlin :
init {
    System.loadLibrary("api-keys")
}
external fun getKeys() : String

For Java :
public native String getKeys();
static {
        System.loadLibrary("api-keys");
 }

Right Click on this method and Create this method in api-keys.c 

Now Open api-keys.c file and In the Return Statement Write the key.

So That's Guys. We have Successfully Implement NDk in Our Project.

For Any Query Contact on Instagram -> https://www.instagram.com/d2dreamdevelopers

Thank You !!! Share We Your Friends And Don't Forget to Subscribe our Channel.

Post a Comment

0 Comments