Android NDK



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:

The ndk content was located in a sub directory below NDK - android-ndk-r19, not as in the previous Unity versions. Giving unity the new path did not work: C: Program Files Unity Hub Editor 2019.3.0f1 Editor Data PlaybackEngines AndroidPlayer NDK android-ndk-r19 It was definitly there but showed as missing. For everyone struggling for ndk do this steps. 1.Download android-ndk-r19c from the official page. 3.Go into the extracted folder and find source.properties 4.Open it and change Pkg.Revision to Pkg.Revision = 19.0.5232133 5.Now Enjoy! Android provides Native Development Kit (NDK) to support native development in C/C, besides the Android Software Development Kit (Android SDK) which supports Java. NDK is a complex and advanced topics.

  • 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

The NDK package includes a set of documentation that describes the capabilities of the NDK and how to use it to create shared libraries for your Android applications. In this release, the documentation is provided only in the downloadable NDK package. The Android NDK is a toolset that lets you implement parts of your app in native code, using languages such as C and C.

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:

  1. 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.
  2. 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.
Android ndk 19b

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?

Prerequisite

Android

To use Android NDK support in your application, you need to download the following three tools:

  1. LLDB: It is used by Android Studio to debug the native code present in your project.
  2. NDK: Native Development Kit(NDK) is used to code in C and C++ i.e. native languages for Android.
  3. 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):

  1. Add
  2. Subtract
  3. Multiply
  4. Divide

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.

Closing note

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.

Happy Learning :)

Team MindOrks!

Terms and Conditions

This is the Android Software Development Kit License Agreement

1. Introduction

1.1 The Android Software Development Kit (referred to in this License Agreement as the 'SDK' andspecifically including the Android system files, packaged APIs, and Google APIs add-ons) islicensed to you subject to the terms of this License Agreement. This License Agreement forms alegally binding contract between you and Google in relation to your use of the SDK.1.2 “Android” means the Android software stack for devices, as made available under the AndroidOpen Source Project, which is located at the following URL: http://source.android.com/, as updatedfrom time to time.1.3 'Google' means Google Inc., a Delaware corporation with principal place of business at 1600Amphitheatre Parkway, Mountain View, CA 94043, United States.

2. Accepting this License Agreement

2.1 In order to use the SDK, you must first agree to this License Agreement. You may not use theSDK if you do not accept this License Agreement.2.2 By clicking to accept, you hereby agree to the terms of this License Agreement.2.3 You may not use the SDK and may not accept the License Agreement if you are a person barredfrom receiving the SDK under the laws of the United States or other countries including the countryin which you are resident or from which you use the SDK.2.4 If you are agreeing to be bound by this License Agreement on behalf of your employer or otherentity, you represent and warrant that you have full legal authority to bind your employer or suchentity to this License Agreement. If you do not have the requisite authority, you may not acceptthe License Agreement or use the SDK on behalf of your employer or other entity.

3. SDK License from Google

3.1 Subject to the terms of this License Agreement, Google grants you a limited, worldwide,royalty-free, non-assignable and non-exclusive license to use the SDK solely to developapplications to run on the Android platform.3.2 You agree that Google or third parties own all legal right, title and interest in and to theSDK, including any Intellectual Property Rights that subsist in the SDK. 'Intellectual PropertyRights' means any and all rights under patent law, copyright law, trade secret law, trademark law,and any and all other proprietary rights. Google reserves all rights not expressly granted to you.3.3 You may not use the SDK for any purpose not expressly permitted by this License Agreement.Except to the extent required by applicable third party licenses, you may not: (a) copy (except forbackup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, or createderivative works of the SDK or any part of the SDK; or (b) load any part of the SDK onto a mobilehandset or any other hardware device except a personal computer, combine any part of the SDK withother software, or distribute any software or device incorporating a part of the SDK.3.4 You agree that you will not take any actions that may cause or result in the fragmentation ofAndroid, including but not limited to distributing, participating in the creation of, or promotingin any way a software development kit derived from the SDK.3.5 Use, reproduction and distribution of components of the SDK licensed under an open sourcesoftware license are governed solely by the terms of that open source software license and not thisLicense Agreement.3.6 You agree that the form and nature of the SDK that Google provides may change without priornotice to you and that future versions of the SDK may be incompatible with applications developedon previous versions of the SDK. You agree that Google may stop (permanently or temporarily)providing the SDK (or any features within the SDK) to you or to users generally at Google's solediscretion, without prior notice to you.3.7 Nothing in this License Agreement gives you a right to use any of Google's trade names,trademarks, service marks, logos, domain names, or other distinctive brand features.3.8 You agree that you will not remove, obscure, or alter any proprietary rights notices (includingcopyright and trademark notices) that may be affixed to or contained within the SDK.

4. Use of the SDK by You

4.1 Google agrees that it obtains no right, title or interest from you (or your licensors) underthis License Agreement in or to any software applications that you develop using the SDK, includingany intellectual property rights that subsist in those applications.4.2 You agree to use the SDK and write applications only for purposes that are permitted by (a)this License Agreement and (b) any applicable law, regulation or generally accepted practices orguidelines in the relevant jurisdictions (including any laws regarding the export of data orsoftware to and from the United States or other relevant countries).4.3 You agree that if you use the SDK to develop applications for general public users, you willprotect the privacy and legal rights of those users. If the users provide you with user names,passwords, or other login information or personal information, you must make the users aware thatthe information will be available to your application, and you must provide legally adequateprivacy notice and protection for those users. If your application stores personal or sensitiveinformation provided by users, it must do so securely. If the user provides your application withGoogle Account information, your application may only use that information to access the user'sGoogle Account when, and for the limited purposes for which, the user has given you permission todo so.4.4 You agree that you will not engage in any activity with the SDK, including the development ordistribution of an application, that interferes with, disrupts, damages, or accesses in anunauthorized manner the servers, networks, or other properties or services of any third partyincluding, but not limited to, Google or any mobile communications carrier.4.5 You agree that you are solely responsible for (and that Google has no responsibility to you orto any third party for) any data, content, or resources that you create, transmit or displaythrough Android and/or applications for Android, and for the consequences of your actions(including any loss or damage which Google may suffer) by doing so.4.6 You agree that you are solely responsible for (and that Google has no responsibility to you orto any third party for) any breach of your obligations under this License Agreement, any applicablethird party contract or Terms of Service, or any applicable law or regulation, and for theconsequences (including any loss or damage which Google or any third party may suffer) of any suchbreach.

5. Your Developer Credentials

5.1 You agree that you are responsible for maintaining the confidentiality of any developercredentials that may be issued to you by Google or which you may choose yourself and that you willbe solely responsible for all applications that are developed under your developer credentials.

6. Privacy and Information

6.1 In order to continually innovate and improve the SDK, Google may collect certain usagestatistics from the software including but not limited to a unique identifier, associated IPaddress, version number of the software, and information on which tools and/or services in the SDKare being used and how they are being used. Before any of this information is collected, the SDKwill notify you and seek your consent. If you withhold consent, the information will not becollected.6.2 The data collected is examined in the aggregate to improve the SDK and is maintained inaccordance with Google's Privacy Policy.NDK

7. Third Party Applications

7.1 If you use the SDK to run applications developed by a third party or that access data, contentor resources provided by a third party, you agree that Google is not responsible for thoseapplications, data, content, or resources. You understand that all data, content or resources whichyou may access through such third party applications are the sole responsibility of the person fromwhich they originated and that Google is not liable for any loss or damage that you may experienceas a result of the use or access of any of those third party applications, data, content, orresources.7.2 You should be aware the data, content, and resources presented to you through such a thirdparty application may be protected by intellectual property rights which are owned by the providers(or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell,distribute or create derivative works based on these data, content, or resources (either in wholeor in part) unless you have been specifically given permission to do so by the relevant owners.7.3 You acknowledge that your use of such third party applications, data, content, or resources maybe subject to separate terms between you and the relevant third party. In that case, this LicenseAgreement does not affect your legal relationship with these third parties.

8. Using Android APIs

8.1 Google Data APIs8.1.1 If you use any API to retrieve data from Google, you acknowledge that the data may beprotected by intellectual property rights which are owned by Google or those parties that providethe data (or by other persons or companies on their behalf). Your use of any such API may besubject to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute orcreate derivative works based on this data (either in whole or in part) unless allowed by therelevant Terms of Service.8.1.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree that youshall retrieve data only with the user's explicit consent and only when, and for the limitedpurposes for which, the user has given you permission to do so.

9. Terminating this License Agreement

9.1 This License Agreement will continue to apply until terminated by either you or Google as setout below.9.2 If you want to terminate this License Agreement, you may do so by ceasing your use of the SDKand any relevant developer credentials.9.3 Google may at any time, terminate this License Agreement with you if:(A) you have breached any provision of this License Agreement; or(B) Google is required to do so by law; or(C) the partner with whom Google offered certain parts of SDK (such as APIs) to you has terminatedits relationship with Google or ceased to offer certain parts of the SDK to you; or(D) Google decides to no longer provide the SDK or certain parts of the SDK to users in the countryin which you are resident or from which you use the service, or the provision of the SDK or certainSDK services to you by Google is, in Google's sole discretion, no longer commercially viable.9.4 When this License Agreement comes to an end, all of the legal rights, obligations andliabilities that you and Google have benefited from, been subject to (or which have accrued overtime whilst this License Agreement has been in force) or which are expressed to continueindefinitely, shall be unaffected by this cessation, and the provisions of paragraph 14.7 shallcontinue to apply to such rights, obligations and liabilities indefinitely.

10. DISCLAIMER OF WARRANTIES

10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND THAT THESDK IS PROVIDED 'AS IS' AND 'AS AVAILABLE' WITHOUT WARRANTY OF ANY KIND FROM GOOGLE.10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THESDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOURCOMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE.10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESSOR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.

11. LIMITATION OF LIABILITY

Android11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND ITSLICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT,INCIDENTAL, SPECIAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANYLOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEENAWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING.

Android Ndk Location

12. Indemnification

12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmlessGoogle, its affiliates and their respective directors, officers, employees and agents from andagainst any and all claims, actions, suits or proceedings, as well as any and all losses,liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of oraccruing from (a) your use of the SDK, (b) any application you develop on the SDK that infringesany copyright, trademark, trade secret, trade dress, patent or other intellectual property right ofany person or defames any person or violates their rights of publicity or privacy, and (c) anynon-compliance by you with this License Agreement.

Android Ndk 17

13. Changes to the License Agreement

13.1 Google may make changes to the License Agreement as it distributes new versions of the SDK.When these changes are made, Google will make a new version of the License Agreement available onthe website where the SDK is made available.

14. General Legal Terms

14.1 This License Agreement constitutes the whole legal agreement between you and Google andgoverns your use of the SDK (excluding any services which Google may provide to you under aseparate written agreement), and completely replaces any prior agreements between you and Google inrelation to the SDK.14.2 You agree that if Google does not exercise or enforce any legal right or remedy which iscontained in this License Agreement (or which Google has the benefit of under any applicable law),this will not be taken to be a formal waiver of Google's rights and that those rights or remedieswill still be available to Google.14.3 If any court of law, having the jurisdiction to decide on this matter, rules that anyprovision of this License Agreement is invalid, then that provision will be removed from thisLicense Agreement without affecting the rest of this License Agreement. The remaining provisions ofthis License Agreement will continue to be valid and enforceable.14.4 You acknowledge and agree that each member of the group of companies of which Google is theparent shall be third party beneficiaries to this License Agreement and that such other companiesshall be entitled to directly enforce, and rely upon, any provision of this License Agreement thatconfers a benefit on (or rights in favor of) them. Other than this, no other person or companyshall be third party beneficiaries to this License Agreement.14.5 EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUSTCOMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE SDK. THESELAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE.14.6 The rights granted in this License Agreement may not be assigned or transferred by either youor Google without the prior written approval of the other party. Neither you nor Google shall bepermitted to delegate their responsibilities or obligations under this License Agreement withoutthe prior written approval of the other party.14.7 This License Agreement, and your relationship with Google under this License Agreement, shallbe governed by the laws of the State of California without regard to its conflict of lawsprovisions. You and Google agree to submit to the exclusive jurisdiction of the courts locatedwithin the county of Santa Clara, California to resolve any legal matter arising from this LicenseAgreement. Notwithstanding this, you agree that Google shall still be allowed to apply forinjunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction.November 13, 2012