Android ndk development entry instance

Source: Internet
Author: User

Android ndk development entry instance

Write this to record how my own ndk gets started. It is easy to view in the future, and you will not forget to use a search engine for a messy search. Then we hope to help the new students get started. First, let's look at what others say:

"Ndk Full name: Native Development Kit.

1. ndk is a collection of tools.

* Ndk provides a series of tools to help developers quickly develop C (or C ++) dynamic libraries and automatically package so and Java applications into APK. These tools are of great help to developers.

* The ndk integrates the cross compiler and provides MK files to isolate differences such as CPU, platform, and Abi, developers can create so simply by modifying the MK file (indicating "which files need to be compiled" and "Compilation feature requirements.

* Ndk can automatically package so and Java applications, greatly reducing developers' packaging work.

2. ndk provides a stable and functional API header file statement.

Google explicitly states that this API is stable and supports the currently released API in all subsequent versions. From the ndk version, we can see that these Apis support very limited functions, including: C standard library (libc), standard Math Library (libm), and compression library (libz), log Library (liblog )."

Before in-depth understanding, ndk is regarded as a tool, which enables Java to use the so package compiled by C/C ++. And pack the package into the APK package.

The following is a quick start:

1. Build a development environment (taking windows as an example, similar to Linux)

1. Download The ndk compressed package. Where can I download it using the search engine.

2. decompress the ndk package and configure environment variables. Write the extracted address to the PATH environment variable.

3. Enter ndk-build in the command prompt. If the following error is displayed, rather than ndk-build not found, the ndk environment has been installed successfully. Note that the search engine will tell you how to use earlier ndk versions by entering build/host-setup.sh at a command prompt; but the ndk is updated and the file is gone. You only need to enter ndk-build.

Android ndk: cocould not find application project directory!

Android ndk: Please define the ndk_project_path variable to point to it.
/Home/braincol/workspace/Android/android-ndk-r5/build/CORE/build-local.mk: 85: *** Android ndk: aborting. Stop.

4. How to install cygwin and use the search engine to install cygwin. In cygwin installation process, may be slow, must install the project have make and GCC; it is recommended to install the following packages: autoconf2.1, automake1.10, binutils, GCC-core, gcc4-core, GDB, the latest versions of PCRE and PCRE-devel are installed. After the installation is complete, run cygwin and enter "make-V" and "gcc-V" to check whether the installation is successful. Make must be later than 3.81.

5. After the preceding tasks are completed, the basic development environment is set up.

2. Write Java code

1. Create an android project testndk and create the testndk. Java file.

Testndk. Java:

package com.blueeagle.example;import android.app.Activity;import android.widget.TextView;import android.os.Bundle;public class TestNDK extends Activity{    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        TextView  myTextView = new TextView(this);        myTextView.setText( stringTestNdk() );        setContentView(myTextView);    }    public native String  stringTestNdk ();    public native String  stringTestNdk2 ();    static {        System.loadLibrary("testNDK");    }}

 

2. Some necessary instructions

static {System.loadLibrary("testNDK ");}

It indicates that testndk will be loaded when the program starts to run, and the code declared in the static area will be executed before the oncreate method. If the program has multiple classes and the testndk class is not the entrance of your application, then testndk (the complete name is lib testndk. so) This library will be loaded when testndk is used for the first time.

public native String stringTestNdk ();public native String stringTestNdk 2();

We can see that the declaration of the two methods contains the native keyword, which indicates that the two methods are local methods, that is, these two methods are implemented through local code (C/C ++, in Java code, it is just declaration.

Compile the project with eclipse to generate the corresponding. Class file. This step must be completed before the next step, because the corresponding. Class file is used to generate a. h file. The error message is not considered for the moment.

3. Generate a. h file

Before writing a C/C ++ file, you need to use the javah tool to generate the corresponding. h file, and then write the corresponding C/C ++ code according to this. h file.

Go to the created testndk project directory and view the project file androidmanifest. XML assets bin default. properties Gen res SRC and create an ndk folder. the H file is generated.

Run javah-classpath bin-D ndk com. blueeagle. example. testndk in the project directory.

Here-classpath indicates the class path;-D ndk indicates the directory where the generated. h file is stored; com. blueeagle. example. testndk indicates the complete class name.

Now we can see an additional. h file in the ndk Directory: com_blueeagle_example_testndk.h; after opening it, we can see the. H content:

Com_blueeagle_example_testndk.h:

#include <jni.h>#ifndef _Included_com_blueeagle_example_testNDK#define _Included_com_blueeagle_example_testNDK#ifdef __cplusplusextern "C" {#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

 

In the above Code, jniexport and jnicall are JNI macros, which are not required in Android JNI. Of course, there is no mistake in writing them.

The function name is long but is named in the format of java_pacakege_class_mathod.

That is to say:

The stringtestndk () method in testndk. Java corresponds to the java_com_blueeagle_example_testndk _ stringtestndk () method in C/C ++.

The stringtestndk2 () method in testndk. Java corresponds to the java_com_blueeagle_example_testndk _ stringtestndk2 () method in C/C ++.

Note the following annotations:

Signature: () ljava/lang/string;

() Ljava/lang/string;

() Indicates that the function parameter is null (null here refers to no other parameters except jnienv * And jobject. jnienv * And jobject are two necessary parameters of all JNI functions, indicates the JNI environment and corresponding Java class (or object), respectively ),

Ljava/lang/string; indicates that the return value of the function is a string object of Java.

3. compile C/C ++ files

Testndk. C:

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

 

The java_com_blueeagle_example_testndk_stringtestndk method is implemented here, while the java_com_blueeagle_example_testndk_stringtestndk2 method is not implemented because it is in testndk. java only calls the stringtestndk () method, so it does not matter if the stringtestndk 2 () method is not implemented. However, we recommend that you implement all the local methods defined in Java.

The java_com_blueeagle_example_testndk_stringtestndk function simply returns the "Hello test ndk! "Jstring object (corresponding to the string object in Java ).

The testndk. c file has been compiled, and the. h file is useless.

 

4. compile and generate corresponding Libraries

1 first, you need to write the Android. mk File

Create an android. mk file in the directory of testndk. C at the same level.

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. Next we will explain it line by line:

Local_path: = $ (call my-DIR)

The local_path variable must be defined in an android. mk file. It is used to search for source files in the Development tree. In this example, the macro function 'my-dir' is provided by the compilation system and used to return the current path (that is, the directory containing the Android. mk file ).

Include $ (clear_vars)

Clear_vars is provided by the compilation system, specifying that GNU makefile can clear 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

The target object to be compiled. The local_module variable must be defined to identify each module you describe in the Android. mk file. The name must be unique and contain no spaces.

Note: The compilation system automatically generates the appropriate prefix and suffix. In other words, a shared library module named 'hello-JNI 'will generate 'libello-JNI. so 'file.

Important Notes:

If you name the library 'libtestndk', the compiling system will not add any lib prefix or generate libfoo. so, this is to support Android from the source code of the Android platform. MK file, if you do need to do so.

Local_src_files: = testndk. c

The local_src_files variable must contain the C or C ++ source code files to be compiled and packaged into the module. Note that you do not need to list header files and contained files here, because the compilation system will automatically find the dependent files for you; just list the source code files directly transmitted to the compiler.

Note that the default C ++ source code file extension is '. CPP '. it is also possible to specify a different extension. As long as you define the local_default_cpp_extension variable, do not forget the starting dot (that is '. cxx ', not 'cxx ')

Include $ (build_shared_library)

Build_shared_library indicates compiling and generating shared libraries. It is a variable provided by the compilation system and points to a GNU makefile script to collect information from the previous call of 'include $ (clear_vars, define all the information in the local_xxx variable and decide what to compile and how to perform it correctly. The build_static_library variable also indicates generating static libraries: Lib $ (local_module). A, build_executable indicates generating executable files.

2. Compile

Enter the project root directory and enter ndk-build to generate the corresponding library libs/armeabi/testndk. So

5. recompile the hellojni project in eclipse to generate an APK

Recompile the testndk project and add the so package to the APK package to view the result. Display Hello test ndk on the simulator!

 

Hope to help later people!

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.