Getting Started with NDK in Android

Native Development Kit (NDK) is a set of tools that allows using c or c++ code in your android application. It provides the native platform libraries that enables managing native libraries, gives access to physical device components and super useful for cases like developing games or reuse any c/c++ libraries in your app. This post will be helpful for anyone looking to get started with NDK in your android app, and some very basic functions for interacting with native c code.

  • Start a new Android Studio project with type Native C++ Screen Shot 2020-05-09 at 1.56.17 PM
  • Configure your project to use Kotlin/Java & ensure “Use androidx.* artifacts” is checked.
  • In the “Customize C++ Support” Dialog, select “C++11” for “C++ Standard”. This ensures the appropriate “cppFlags” are setup in your project’s build.gradle file. Screen Shot 2020-05-09 at 2.02.52 PM
  • After finish, Android Studio creates your project with the Android and the cpp files.

You might come across this error the first time:

NDK not configured. Download it with SDK Manager

Go to SDK Manager -> SDK Tools -> select NDK (Side By side) – install.  In your App/build.gradle , add the ndkVersion after the externalNativeBuild block like below:

android {

    defaultConfig {
        // ...
        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11"
            }
        }
    }

    buildTypes {
        release {
             // ...
        }
    }

    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.10.2"
        }
    }

    ndkVersion "21.1.6352462"
}
  • After the project is configured and run successfully , you will see the following App screen:

Screen Shot 2020-05-09 at 9.05.31 AM

  • In MainActivity.java , System.loadLibrary function is used to load the native-lib on app startup.
// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}
  • Android NDK supports using C-Make to compile and build c/c++ code for your Android application.
  • If you browse through your project, unlike the standard Android Project, here you will see an additional directory – cpp Screen Shot 2020-05-09 at 2.43.42 PM

    native-lib.cpp is where you can write all your native c/c++ code.

    Sample code with some very basic native functions and their access from Android code can be found at Github .

Leave a comment