Getting started with Android NDK: Android Tutorial
- 1 Getting started with Android NDK: Android Tutorial
- 1.1 Getting started with Android NDK: Android Tutorial
- 1.2 How to get started with Android Studio C++ development
- 1.3 What Is the NDK?
- 1.4 Loading HTML files from the file system
- 1.5 Choice of Technology
- 1.6 Take your pick
- 1.7 What is Java Native Interface?
Getting started with Android NDK: Android Tutorial
We all started our journey of programming language with C or C++. After that, some of you might move to Java or Python or something else that will help in some kind of development like Android development or Web development. Talking about Android specifically, we normally use Java or Kotlin for application development. Can we add some C or C++ code in our application? Yes, you can use the code in Android that you have developed during the learning phase of programming language i.e. while learning C or C++.
In this blog, we will learn how to use native language in Android application development. We will discuss the following topics in this blog:
- What is NDK and why to use it?
- What is JNI?
- Some prerequisite
- «Hello World!» example with Android NDK
- The «Calculator App» example with Android NDK
- The disadvantage of using native language
So, let’s get started.
What is NDK and why to use it?
NDK or Native Development Kit is a toolset that is provided by Android to use C or C++ code in our Android application. So, if you are using Android Studio version 2.2 or higher then you can use C or C++ in your Android application.
But for Android development, Java and Kotlin are the recommended languages. So, why to use native languages in Android? Let’ find out the advantages of using native languages in Andoird:
- Very Fast: We all know that to convert a Java code into machine-level code, we need to go to JVM and then to JNI to perform the operations. Same is with Kotlin also because Kotlin also runs Java under the hood. While on the other hand, the NDK directly compiles the native code i.e. the C or C++ code into machine level language by generating a .so file. So, you need not perform the intermediate steps that were required in the case of Java/Kotlin.
- Code Re-usability: You can reuse the code written in C or C++ for different platform in your Android application. You can use the code that you wrote while learning C or C++ or the codes of other developers in your Android application.
So, whenever you want to make some high-performance applications for great speed or want to use some preexisting code written in some native language then you can use C or C++. Due to the speed factor, most of the game developers use C or C++ for writing the code for their games. Also, it becomes an easier task for them to use their C or C++ code in the Android application.
What if you want to use both Java/Kotlin and native language in your application? This is the most used case. Is it possible to use Java code from C++ and vice-versa? How will the Java code communicate with the native code? The communication is done by JNI. What is this JNI? Let’s find out.
What is JNI?
JNI or Java Native Interface is the interface between your Java/Kotlin and the C/C++ code. It defines a way for the byte code that is generated by the Android to communicate with the native code. Java or Kotlin Code uses JNI to communicate with the C or C++ code.
Before getting started with our first «Hello World!» application with the Android NDK, let’s have a look at the Native primitive data types that we will be using in our code later.
So, you can notice that all you need to do is just add » j» before any data type. For example, int is written as » jint«, byte is written as » jbyte» and so one.
Some SDK tools need to be added in Android Studio to use NDK support. Let’s see what are those tools and how to download those tools?
To use Android NDK support in your application, you need to download the following three tools:
- LLDB: It is used by Android Studio to debug the native code present in your project.
- NDK: Native Development Kit(NDK) is used to code in C and C++ i.e. native languages for Android.
- CMake: It is an open-source system that manages the build process in an operating system and a compiler-independent manner.
Let’s see how to download all the above mentioned in Android Studio.
Following is the screen that you see when you open Android Studio. Click on the Configure button that is present in the bottom right corner of the Welcome screen.
Now select SDK Manager from the list available to you.
Under the SDK Tools tab, select LLDB, NDK, and CMake. After selecting these three, click on OK and wait for the tools to download.
Close the SDK Manager and get back to Welcome screen of Android Studio.
«Hello World!» example with Android NDK
So, we are done with the prerequisites of Android NDK. Now, let’s quickly move on to the classic «Hello, World!» example using Android NDK. Follow the below steps:
Step1: Open the Welcome screen of the Android Studio and create a new project.
Step2: Select the Native C++ template and click on Next. This will include all the files necessary for the use of native language in Android.
Step3: Enter the details of the project like Project Name, Package Name, and all other relevant information and click on Next.
Step4: You can choose the compiler that you want to use for compiling the C++ code. We are using the default settings. Click on Finish.
Following is the project structure that you will get after using the C++ template.
Here you can see that apart from the usual java directory, we are having one more directory named cpp that contains all the native files and CMakeLists.txt file. By default, we are having one native-lib.cpp file that contains the C++ code. Following is the code of the native-lib.cpp file:
Following is the description of the above code:
- Above code is C++ code, so as like normal C++ file, we can include some libraries by using:
- Here, you have to follow the combination of PackageName_ActivityName_MethodName.
- In the above example, com_mindorks_androidndkexample is the package name, MainActivity is the activity/file name and stringFromJNI is the method that returns a string from the native code and will be called from the Java/Kotlin code.
- Finally, in the return statement, you can see that we are returning the hello string from the function.
Till now, we are done with the native part. Now, let’s find out how to call the native functions that we have created from our Kotlin code.
In your Kotlin code i.e. in the MainActivity.kt file, you need to load the native code by calling the System.loadLibrary(«native-lib») method in the init block.
Now, you have to declare a Kotlin external function with the same name as used in the native-lib.cpp file
Finally, you can get the values from the function present in the native-lib.cpp file by calling:
That’s it. All the above code is already present in your project. So, run your application by pressing shift+f10 and see the output.
The «Calculator App» example with Android NDK
We have seen the basic «Hello, World!» example by using the native language. Now, let’s build one calculator app that will take input from the user and will perform the following four actions(we will only cover the logical part):
So, as in the «Hello, World!» example, we first declared a method in the native-lib.cpp file. In the «Calculator App» also, we are going to define four different methods for performing the above four operations.
Here, you can see that we have four functions named add(for the addition of two numbers), sub(for the subtraction of two numbers), multiply(for the multiplication fo two numbers), and divide(for the division of two numbers). The return type of each function is jint. Also, each function is taking two integers as parameters and both are of type jint.
Now, our next task is to load the native-lib file in our Kotlin file. So, we can do that by using the System.loadLibrary(«native-lib») method.
Now, declare four Kotlin external methods with the same name as used in the native-lib file.
That’s it, you are done with all the four functions. Now, you can use these functions according to your need in the Java/Kotlin file. That’s it.
The disadvantage of using native language
The disadvantage associated with using native language is that if you don’t use the APK Split or APK Bundle then using NDK alone will increase the APK size. What happens is that the NDK makes the .so file i.e. the machine executable file based on the Architecture of Android. For example, if we are having mips, x86, armeabi, armeabi-v7a, armeabi-v8a, then the .so file will be generated for all the five architectures. So, if the size of one .so file is 5MB then the application size should be 5MB but in reality, it will be of 5*5 = 25MB.
But if you are using APK Split or APK Bundle, then you will make five different APK for different architecture and you will upload all the five APK on play store. Now, the Play Store must identify the device architecture and then give the desired APK to download.
In this blog, we learned how to use native languages like C and C++ in our Android applications. Usually, when we are dealing with some cross-platform application or we need to build some high-performance application, then we use native languages in our application. Otherwise, it is advised to go with Java or Kotlin.
Hope you learned something new today.
Check our all the Android tutorial here.
Do share this blog with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website .
We begin the development cycle by showing you what to select in your Android Studio options. Below is a step by step instruction on what you need to do.
- Start by creating a project using the Native C++ Project Template as referenced the in the following screenshot.
- Set the application name to Neon Intrinsics, selected Java as the language, and set the minimum SDK to API 19: Android 4.4 (KitKat) as shown in the following screenshot.
- Select Toolchain Default for the C++ Standard as shown in the following screenshot.
The project that you created comprises one activity that is implemented within the MainActivity class, deriving from AppCompatActivity which you can see at app/java/com.example.neonintrinsics/MainActivity.java for further information. The associated view contains only a TextView control that displays the string: “Hello from C++, as you can see in the following image:
To get these results, run the project directly from Android Studio using one of the emulators. To build the project successfully
- You must install CMake along with the Android NDK. You can do this through File > Settings. Then select NDK and CMake on the SDK Tools tab.
Open the MainActivity.java file. The string that is displayed in the app comes from native-lib . The code for this library is in the app/cpp/native-lib.cpp file. That file is used for the implementation.
How to get started with Android Studio C++ development
Supported development platforms
Please refer to the Vuforia Engine Supported Versions page for details on the latest supported versions of Android and Android tools such as Android Studio.
NOTE: This setup guide was written for the Windows 10 64-bit platform with special notes for other operating systems.
If you have already set up the Android SDK and NDK, go directly to Installing Vuforia Engine for Android.
Vuforia Engine requires the Android SDK and the Android NDK for C++ development.
To set up the development environment, install these components in the following order, using the latest versions of the tools with Vuforia Engine:
- Android Studio IDE
- Android SDK
- Android NDK
- Vuforia Engine for Android
In order to develop in Android Studio with C++, install the Android NDK from the SDK Manager. See the Android SDK Packages section.
Install Android Studio
Android Studio provides everything you need to start developing apps for Android, including the Android Studio IDE and the Android SDK tools.
- Download the Android Studio installer from: https://developer.android.com/studio choosing your preferred operating system.
- Once the download has completed, run the installer executable, and follow the official installation instructions to install the IDE.
- Pay attention to the following installation steps:
- In the Configuration Settings Install Locations step of the install wizard the default directory that will be used is C:Program FilesAndroidAndroid Studio . We suggest to select or create a path that is easier to find such as C:DevelopmentAndroid . The SDKs and Vuforia Engine can hereafter be installed in that directory.
Android SDK Packages
Android Studio includes a SDK manager that allows you to install additional SDK components, besides the ones installed with Android Studio, and to update your Android SDK tools.
We recommend running the SDK Manager after the installation of Android Studio, in order to download the necessary components for developing with Vuforia Engine.
- Launch Android Studio
- In the Welcome to Android Studio, click on Configure and select SDK Manager or in Android Studio, click on the SDK Manager icon in the Toolbar.
- In the dialog window that opens, set Android SDK Location to C:DevelopmentAndroidandroid-sdk
- Select the desired tools:
- Android SDK Tools (latest rev.)
- Android SDK Build Tools (latest rev.)
- Android SDK Platform-Tools (latest rev.)
- Google USB Driver (Windows only)
- Android API matching that of your own Android device.
- Android NDK
- Once you have selected all the desired packages, continue to click install and accept the license agreements.
NOTE: the downloads progress is shown at the bottom of the SDK Manager window. Do not exit the SDK Manager or it will cancel the download.
Setting the System Environment Variables
If you plan to work outside of Android Studio and use tools like adb directly, you will need to manually configure Environment Variables on your system for Android development.
If you have chosen a different folder directory than the default, it is necessary to add those directories to your Windows Path:
- In the File Explorer, right-click This PC and select Properties.
- Click the Advanced system settings button to open the System Properties window
- Under the Advanced tab, select Environment Variables and select Variable Path in the System variables window.
- After pressing Edit, scroll to the end of Variable value: and add New variable. Add the full path to the directory at the end of the path, separated by a semicolon from the previous path. In the above example, you would add:
NOTE: The last «» at the end of the Path variable must be included.
Mac OSX: Update the PATH variable to point to the Android SDK Platform-tools directory in the /etc/rc.common file or
Linux: Update your PATH to point to the Android SDK Platform-tools directory. If you use bash shell, add the following to
Installing Vuforia Engine for Android
Vuforia Engine is distributed as a ZIP package for the following platforms:
- Mac OS
To start developing with the Vuforia Engine SDK:
- Download Vuforia Engine for Android
- Extract the contents of the SDK ZIP archive, placing it in your Android development root folder (e.g. C:DevelopmentAndroid on Windows, or /Users/[account]/Development/Android on OSX or Linux)
- As a convention, we will refer to the root directory of your Vuforia Engine for Android development environment as DEVELOPMENT_ROOT
Extracting the SDK will create a directory structure for your Android development environment. This structure ensures that Vuforia Engine sample apps can easily be built and deployed using the Android SDK, Android NDK, and the Android Studio development environment.
Upgrading from a previous version
- See How to Migrate an Android Project for API changes and migration instructions.
Resulting directory structure
To streamline development, we have defined a directory structure that maintains Vuforia Engine and your applications in separate directory trees. This enables the SDK to be updated without the need to modify your source tree.
The extracted SDK archive will create the following directory structure in the vuforia-sdk-android-[ xx-yy-zz ] folder. The pattern xx-yy-zz stands for the version number of Vuforia Engine.
Enabling Developer settings on your handheld device
Android devices require special settings for development.
You will need to:
- Enable installing apps from unknown sources
- On the device, go to Settings > Security and choose Unknown sources. This setting allows direct installation of unsigned APKs from within Eclipse.
- Enable USB debugging
- Go to Settings > Developer Options and enable the USB debugging.
Install the USB driver (Windows only)
- Connect your device to the development PC using the USB cable.
On initial connection, Windows recognizes the new device and attempts to locate a compatible driver. The Android SDK already includes some USB drivers, others can be obtained directly from the device manufacturer.
SDK pre-packaged drivers can be located in the following directory:
Your device will be ready to use when the device driver installation has completed.
Compiling and Running an Android Sample
Vuforia Engine for the Android platform is accessible through a C++ API. The sample applications demonstrate the Image Targets and Model Targets features of Vuforia Engine and shows how an application written in Kotlin can use the C++ API.
The Vuforia Engine Sample can be downloaded from https://developer.vuforia.com/downloads/samples
Once downloaded, extract the sample ZIP package and copy it into the samples folder under your Vuforia Engine installation directory (e.g., C: . Androidvuforia-sdk-android-xx-yy-zzsamples ).
The Vuforia-sample-x-y-z application is a good place to start learning about the SDK, because it shows the main features of the SDK in a single app. This section explains how to use Android Studio to build the source code and create the APK package that can be deployed to the device.
Building a Sample
To build a Vuforia Engine sample for the Android platform, follow these steps:
- Launch Android Studio.
- Select Open an existing Android Studio project from the Quick Start launch page.
- Browse to the …vuforia-sdk-android-xx-yy-zzsamplesVuforia-samples-x-y-zAndroid directory and click OK to open it.
- When opening a sample project for the first time, Android Studio may prompt a dialog asking whether you want to create a Gradle Wrapper for the project; you can answer yes by clicking the OK button:
- Once the project is loaded, open the Build menu and select Make Project to compile the app. This will also create the APK package for deployment; the generated APK files are stored by Android Studio in the app/build/outputs/ sub-directory of the sample project.
Alternatively, you can click Rebuild Project to trigger a clean and full rebuild of the application.
- If you have not already done so, create a license key for your app.
- Add the license key to your app.
Running the Vuforia Engine Samples application
If you click the Run menu item on the toolbar, or on the little arrow icon next to the app menu button, the app will be compiled, installed, and launched on the target device.
Upon startup of the Vuforia Engine Sample app, a main menu is shown on your device, from which you can select between the Image Targets or Model Targets feature:
Select the Image Targets feature to get started.
You have successfully deployed your first application with Vuforia Engine!
Tap the screen once to trigger the camera to focus, or double-tap to go back to the main menu.
If you encounter problems during the installation of the sample app, check the device’s connection settings in Troubleshoot device connection.
In Android Studio, you can see if the device is connected correctly via the Android Profiler, which you can activate if your device is detected and listed under Devices in Android Studio.
Installing an APK using ADB
You can install an APK onto an Android device by connecting the device to a PC with a USB cord and then connecting to the device using the Android Debug Bridge (ADB).
- Connect the device to the developer desktop environment with a USB cable.
- Open a bash shell or Windows Command Line and execute:
The output should show the attached device:
3. To install the application, navigate to the folder containing the downloaded APK. In our example C:Temp and install APK using adb.
4. If the device list is empty, or a given device is not listed, kill the ADB server by executing:
5. Execute adb devices again to restart the server, re-detect devices, and try again.
What Is the NDK?
The NDK is a toolset that enables the development of Android apps using C, C++ and other native code languages, compiling code into applications that can run on Android devices. Using the NDK is generally not recommended because apps may experience a performance hit, suffer from compatibility issues, be harder to debug, and reduce flexibility. What the NDK guarantees is an increase in app complexity and connectivity from interfacing with native code.
The previous statements may sound discouraging but there are good use cases for the NDK. This includes computationally intensive apps like games, game engines, signal processing and physics simulations. Another good use case is reusing existing libraries written in C/C++. This means you can leverage a large collection of native code libraries available online.
Make sure to balance the pros and cons of using the NDK before deciding if itвЂ™s worth the extra complexity. You should never base your decision on your preferred language even if you are an expert in C or C++.
Loading HTML files from the file system
A big advantage of using a WebView inside an installable application is that you can store assets inside the app. This lets your app work offline and improves load times, since the WebView can retrieve assets directly from the local file system.
In your project, create the assets directory in main ( src/main/assets ).
Generally it’s good practice to keep your web files in a subdirectory, so create a www directory and put all your web content in it.
Once you have everything in your assets directory, it’s as simple as loading in the appropriate file:
You’ll want to tweak the shouldOverrideUrlLoading method so it opens a browser for non-local pages:
Now you are set to build a great WebView app!
For tips on getting the visuals just right, see Pixel-Perfect UI in the WebView.
If you run into trouble, the Chrome DevTools are your friends. See Remote Debugging on Android to get started.
Content available under the CC-By 3.0 license
Choice of Technology
This series makes a specific technology choice, which I believe is the best for writing business apps that need to have a lot of logic on the client side. We have to bear in mind a couple of things however:
C++ is hard, the language itself is full featured, it has just about everything and the kitchen sink. You are free to use the subset of features you need though. The standard library is huge and you will never know everything about it, but it is very well documented and very clear, and does everything you need.
C++ is modern, the latest revision dates back from 2017, and is fully supported on our target platforms, C++ 2020 is coming fast with a few improvements too, and there is no doubt it will be included in our toolchains as soon as it is ready. By modern, I mean it has automatic memory management (no more new and delete), it has lambda, auto, the best time management library that exists, a great threading library and what not (all in the standard library).
C++ is portable, it allows you to use the latest things on all the platforms, including older platforms, my big project works on iOS 9 32bit. This is because the library is included in your build and you don’t depend on stuff being there on the target platform. With Android Java, we still cannot fully use Java 8 which came out in 2014.
C++ is fast, this goes without saying. Your binaries are small and they run at… native speed.
Take your pick
If you want to develop Android apps, step one is picking a language. The differences between the various Android programming languages can be a little complex and nuanced.
But what matters more than the language itself is the tool it is attached to, and the main features and goals of said tool.
The languages you might consider learning for Android development include:
- Java – Java is an official language of Android development and is supported by Android Studio. It has been an official language longer than Kotlin, and it is also popular outside of Kotlin development for many other purposes. Java and Android Studio have a steep learning curve, however.
- Kotlin – Kotlin is another official Android language. It is similar to Java in many ways but is a little easier to get your head around. It is also now Google’s preferred language of choice, though it is not as widely used outside of Android Studio. This may make it slightly less appealing for those hoping to work as developers across numerous projects.
- C++ — Android Studio also supports C++ with the use of the Java NDK. This allows for native coding applications, which can be handy for things like games. C++ is more complicated though, and this option is mostly only going to appeal to large, professional teams. C++ is also supported by Unreal Engine.
- C# — C# is a more beginner-friendly alternative to C or C++ that obfuscates more code. It is also a little less difficult than Java, though the two languages are extremely similar. It’s supported by some very handy tools like Unity and Xamarin, which are great for game development and cross-platform development. C# with Unity is the best option for many mobile game developers.
- LUA (Corona) – Another cross-platform tool built on LUA. It massively simplifies the app-building process while stilling allowing you to call native libraries.
When it’s time to develop Android apps, Jave remains one of the two official options. This means that it has a lot of support from Google. Most non-game apps were probably built with either Java or Kotlin.
The number one way to develop Android apps, is to go ahead and download Android Studio. This is a piece of software called an IDE, or Integrated Development Environment. It will come packaged with the Android SDK (a set of tools to facilitate Android development specifically) and this will give you everything you need in one place to get up and running.
Official documentation from Google will refer to Android Studio and Java (or Kotlin), and you’ll be able to find a lot of support online.
Java itself was released by Sun Microsystems back in 1995 and is used for a wide range of programming applications. Even as Google has made apparent its preference for Kotlin, Java is so entrenched and familiar that many development teams have chosen to stick with it.
Unfortunately, Java is also complicated and isn’t a great “first language.” Things get more complicated still once you add the Android SDK into the mix; a first-time coder can struggle to know what’s Java and what’s Android! Java is an object-oriented programming language with confusing topics like constructors, null pointer exceptions, checked exceptions and more. It’s not terribly readable and you’ll use a lot of “boilerplate” code doing simple things. Development using this route also requires a basic understanding of concepts like Gradle, the Android Manifest and the markup language XML.
That’s not to say that Java is a bad language – far from it. Not only would it be wrong to call any language “bad,” but it’s also true that most of the inconveniences of Java are actually there for our own good and encourage clean code. A lot of people love Java for this reason, and it’s also one of the most versatile and widely used. According to the PYPL (PopularitY of Programming Languages) table, Java is the most sought after programming language among employers.
Android Studio, has also been going from strength to strength over the last few years. Features like a visual designer and suggestions make the process a fair bit smoother, while advanced, powerful features are being added all the time to give developers access to things like cloud storage with easy implementation. It’s worth getting aboard, even if this rapid progress does make it hard to keep up sometimes (especially if you’re some poor guy who writes about this stuff for a living!).
What is Java Native Interface?
Java Native Interface defines the way managed code (written in Java) interacts with native code (written in C/C++). It’s vendor-neutral and supports loading code from dynamic shared libraries. JNI allows you to call native methods from Java and vice versa.
Let’s elaborate on this one a bit. What does «native» code mean at all? «Native» means that the code is native to the processor that your code is compiled for. C/C++ are compiled directly into CPU-understandable instructions without any intermediate mechanisms like JVM. For more details, you can refer to these guides:
Integrate cloud based services from Back-end as a Service (BaaS) providers, Kinvey, Parse and App42, with components for popular BaaS services like push notifications, authentication, and storage. You get easy access to these common services in the cloud without having to build them yourself or maintain them. Add user authentication to your apps. Use push notifications to engage your users. Access data and object storage in the cloud.