1. Create a new Project
- Open Android Studio (I’m using version 3.5.3).
- Click Start a new Android Studio Project.
- Under the Phone and Tablet tab select Add No Activity and click Next.
- Fill in the following information:
- Language: Kotlin
- Minimum API level: API 16: Android 4.1 (Jelly Bean)
- This project will support instant apps: Leave it unchecked
- Use androidx.* artifacts: Leave it checked
- Choose your own Name, Package name and Save location.
- Click Finish.
2. Create a new folder
This folder will hold your native project files (C/C++ files, the CMakeLists.txt file etc.).
- Open the Project pane from the left side of the IDE.
- Select the Project view.
- Navigate to app -> src.
- Right click the main folder and select New -> Directory.
- Type cpp as the directory name and click OK.
Note
You can name this folder anything you want.
3. Create the C/C++ files
- Right click the cpp folder and select New -> C/C++ Source File.
- Provide the following information and click OK:
- Name: main
- Type: cpp
- Create an associated header: Leave it unchecked
- Click OK.
Note
You can name this file anything you want.
4. Configure CMake
Now you will configure CMake and tell it how to build your native project.
- Right click the cpp folder and select New -> File.
- Type CMakeLists.txt as the file name and click OK.
- Add the following:
cmake_minimum_required(VERSION 3.6.0) add_library(native-library SHARED main.cpp)
Note
At this point, if you check the Android view, you will notice that the cpp folder is not yet visible. That’s because you have to tell Gradle about the CMakeLists.txt file.
5. Configure Gradle
Now all you have to do is let Gradle know about the native project.
After this, when you build your project, Gradle tells CMake to build the native library and packages it with your APK.
- Return to the Android view.
- Open the build.gradle (Module: app) file.
- Add the following block inside the android block (lets say after the buildTypes block):
externalNativeBuild { cmake { path file('src/main/cpp/CMakeLists.txt') } }
- Save the file and click Sync Now.
Note
You can now see the cpp folder in the Android view.
Leave a Reply