"Go" Android ndk Development Starter Instance

Source: Internet
Author: User

The purpose of writing this is to document how my own ndk is getting started. Easy to view later, and do not forget to use search engines and a random search. Then hope to help people who have just learned to get started.

Turn first to what others say:

"NDK Full Name: Native development Kit.

1. The NDK is a collection of tools.

* The NDK provides a range of tools to help developers quickly develop C (or C + +) dynamic libraries and automatically package so and Java applications together as APK. These tools are great for developers.

* NDK integrates the cross compiler, and provides the corresponding MK file isolation CPU, platform, ABI and other differences, developers only need to simply modify the Mk file ("which files need to compile", "compile feature requirements", etc.), you can create a so.

* The NDK can automatically package so and Java applications together, greatly reducing the developer's packaging effort.

2. The NDK provides a stable, functionally limited API header file declaration.

Google expressly declares that the API is stable and supports the currently published API in all subsequent releases. As seen from this version of the NDK, these APIs support a very limited number of features, including: C standard library (LIBC), Standard math Library (LIBM), compression library (LIBZ), log Library (Liblog). ”

Before you dive in, think of the NDK as a tool that enables Java to use the so package compiled by C + +. and bring this package together into the APK package.

Get started here:

First, the development environment to build (under the Windows platform for example, under the Linux platform similar)

1. Download the NDK package and download it from the search engine.

2. Unzip the NDK package and configure the environment variables. Writes the extracted address to the environment variable in path

3. Enter Ndk-build at the command prompt if the following error appears instead of Ndk-build not found, the NDK environment has been installed successfully. In particular, the search engine will tell some of the earlier versions of the NDK to be used, at the command prompt, to enter build/host-setup.sh, but the NDK has been updated and the file is gone. You just need to enter the Ndk-build.

Find Application project directory!  /home/braincol/workspace/android/android-ndk-r5/build/core/build-local.mk:* * * * Android NDK: Aborting. Stop.

4. Cygwin installation, as to how to install, from where to install also to use the search engine bar. During the Cygwin installation process, it may be slow and must be installed with make and GCC, and it is recommended to install the following packages: autoconf2.1, automake1.10, Binutils, Gcc-core, Gcc4-core, GDB, Pcre, Pcre-devel, install the latest version. After installation, run Cygwin, enter "Make-v" and "gcc-v" to detect whether the installation is successful, and make version is above 3.81.

5. After the completion of the above tasks, it indicates that the basic development environment has been built.

Second, write Java code

1. Build an Android project TESTNDK, create the Testndk.java file.

Testndk.java:

 Packagecom.blueeagle.example;Importandroid.app.Activity;ImportAndroid.widget.TextView;ImportAndroid.os.Bundle; Public classTestndkextendsactivity{@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); TextView Mytextview=NewTextView ( This);        Mytextview.settext (STRINGTESTNDK ());    Setcontentview (Mytextview); }     Public nativeString stringtestndk ();  Public nativeString STRINGTESTNDK2 (); Static{system.loadlibrary ("Testndk"); }}

2. Some of the necessary notes

Static {    system.loadlibrary ("TESTNDK");}

Indicates that the TESTNDK is loaded when the program starts running, and the code for the static zone declaration is executed before the OnCreate method.

If there are multiple classes in the program, and if the TESTNDK class is not the entry for your application, then TESTNDK (the full name is Lib Testndk.so) will be loaded the first time you use the Testndk class.

 Public native String stringtestndk ();  Public native String STRINGTESTNDK 2 ();

You can see the native keyword in the declaration of both methods, which means that the two methods are local methods, that is, the two methods are implemented by local code (c + +), which is simply a declaration in Java code.

Compile the project with Eclipse and generate the corresponding. class file, which must be completed before the next step, because the. h file is required for the corresponding. class file. Temporarily do not consider the error message.

3. Generate the. h file

Before you write C + + files, you need to use the Javah tool to generate the corresponding. h file, and then write the corresponding C + + code according to the. h file.

Go to the TESTNDK project directory you just created, view the project file: androidmanifest.xml Assets bin Default.properties Gen Res src and create a new NDK folder to create the. h file.

Executed under the project directory: Javah-classpath bin-d ndk Com.blueeagle.example.TestNDK

Here-classpath represents the path of the class, and the-D NDK represents the directory where the generated. h file is stored; Com.blueeagle.example.TestNDK is the complete class name.

Now you can see one more. h file in the NDK directory: Com_blueeagle_example_testndk.h; When opened, you can see the contents of the. h:

Com_blueeagle_example_testndk.h:

#include <jni.h>#ifndef _included_com_blueeagle_example_testndk#define _included_com_blueeagle_example_testndk#ifdef __ CplusplusexternC{#endif/** CLASS:COM_BLUEEAGLE_EXAMPLE_TESTNDK * METHOD:STRINGTESTNDK * Signature: () ljava/lang/string;*/jniexport jstring jnicall java_ com_blueeagle_example_testndk_stringtestndk (jnienv*, jobject);/** CLASS:COM_BLUEEAGLE_EXAMPLE_TESTNDK * METHOD:STRINGTESTNDK2 * Signature: () ljava/lang/string;*/jniexport jstring jnicall java_ com_blueeagle_example_testndk_stringtestndk2 (jnienv*, jobject); #ifdef __cplusplus} #endif #endif

The Jniexport and Jnicall in the above code are JNI macros that are not required in the jni of Android and, of course, are not error-written.

The function name is relatively long but is named exactly as: Java_pacakege_class_mathod form.

Other words:

The STRINGTESTNDK () method in Testndk.java corresponds to the Java_com_blueeagle_example_testndk_ stringtestndk () method in C/

The STRINGTESTNDK2 () method in Testndk.java corresponds to the Java_com_blueeagle_example_testndk_ stringTestNdk2 () method in C/

Note the following comments:

Signature: () ljava/lang/string;

() ljava/lang/string;

() indicates that the function's argument is empty (null here means that there are no parameters other than jnienv *, Jobject, jnienv*, Jobject is the two parameters required for all JNI functions, representing the JNI environment and the corresponding Java class (or object) itself),

ljava/lang/string; A String object that represents the return value of the function as Java.

Third, write A/C + + file

TESTNDK.C:

#include <string.h><jni.h>jstringjava_com_blueeagle_example_testndk_stringtestndk ( JNIEnv* env,                                                  jobject thiz) {    return (*env)->newstringutf (env, "Hello Test NDK!") );}

This only implements the Java_com_blueeagle_example_testndk_stringtestndk method, and JAVA_COM_BLUEEAGLE_EXAMPLE_TESTNDK_STRINGTESTNDK2 Method is not implemented because only the STRINGTESTNDK () method is called in Testndk.java, so the Stringtestndk 2 () method is not implemented, but it is advisable to implement all native methods defined in Java.

The JAVA_COM_BLUEEAGLE_EXAMPLE_TESTNDK_STRINGTESTNDK function simply returns a Jstring object with a content of "Hello Test NDK!" (corresponding to a string object in Java).

The Testndk.c file has been written, and the. h file is no longer available.

Iv. compiling and generating the corresponding library

1 first need to write Android.mk file

Create a new android.mk file in Testndk.c's sibling directory

Local_path: = $ (call my-dir) include $ (clear_vars) local_module    := testndk
Local_src_files: = testndk.cinclude $ (build_shared_library)

This androd.mk file is very short, let's take a line-by-row explanation:

Local_path: = $ (call My-dir)

A android.mk file must first define the Local_path variable. It is used to find source files in the development tree. In this example, the macro function ' My-dir ', provided by the compilation system, is used to return the current path (that is, the directory containing the android.mk file).

Include $ (clear_vars)

Clear_vars is provided by the build system, specifying that GNU makefile clears many local_xxx variables for you (such as Local_module, Local_src_files, local_static_libraries, etc...) ,
Except Local_path. This is necessary because all the compilation control files are in the same GNU make execution environment, and all the variables are global.

Local_module: = Testndk

To compile the target object, the Local_module variable must be defined to identify each module that you describe in the Android.mk file. The name must be unique and does not contain any spaces.

Note: The compilation system will automatically generate the appropriate prefix and suffix, in other words, a shared library module named ' Hello-jni ' will generate ' libhello-jni.so ' files.

Important points to note:

If you name the library ' LIBTESTNDK ', the compiler will not add any LIB prefixes and will generate libfoo.so, which is to support android.mk files from the source code of the Android platform, if you really need to.

Local_src_files: = testndk.c

The local_src_files variable must contain a C or C + + source code file that will be compiled into a module. Note that you do not have to list header files and include files here, because the compilation system will automatically find the dependent files for you; Just list the source code files that are passed directly to the compiler.

Note that the default C + + source file extension is '. cpp '. It is also possible to specify a different extension, as long as the local_default_cpp_extension variable is defined, do not forget to start the small dot (i.e. '. Cxx ' instead of ' cxx ')

Include $ (build_shared_library)

Build_shared_library means compiling a shared library, which is a compiled system-supplied variable, pointing to a GNU makefile script, responsible for collecting since the last call to ' include $ (clear_vars) ', defined in Local_ XXX variable, and decide what to compile and how to do it correctly. There are also build_static_library variable representations to generate a static library: lib$ (Local_module). A, build_executable represents the build executable.

2 second to compile

Go to the project root and enter Ndk-build to generate the appropriate library libs/armeabi/testndk.so

V. Recompile HELLOJNI project in Eclipse, build apk

Recompile the TESTNDK project and bring the so package into the project APK package to see the results. Display the Hello Test ndk! on the emulator

"Go" Android ndk Development Starter Instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.