Android ndk preliminary 1

Source: Internet
Author: User
Ndk is always troublesome, but it is also a tragedy not to use ndk.

After reading what others have done on the Internet, the ndk is a little different from JNI. The ndk is a little simpler. Ndk R7 does not need Cyg, the company does not go to QQ, it is not easy to put a fake, and too lazy to enter Linux tossing, QQ on Windows, By the way something to do.

How can ndk get rid of it. Download and decompress the package. Configure the environment variables. If ndk-build encounters a problem, use Linux or install cygwin. just delete the prebuild under ndk. Awk conflict

 

First, create one. You know, don't get the sample stuff. You don't know how it came from. It is best to step by step. 1 package COM. example. hellojni; import android. app. activity; import android. OS. bundle; import android. widget. toast; public class hellojni extends activity {/*** @ author thinkinbunny called when the activity is first created. */Public native string stringfromjni (); Public native int resultret (int x, int y); // This is the sum of the added values. I forgot about C, negative complementing/** this is another native method declaration that is ** not * implemented By * 'hello-JNI '. this is simply to show that you can declare as your native * methods in your Java code as you want, their implementation is searched * in the currently loaded native libraries only the first time you call * them. ** trying to call this function will result in a * Java. lang. unsatisfiedlinkerror exception! */Public native string unimplementedstringfromjni ();/** this is used to load the 'hello-jni' library on application startup. the * library has already been unpacked into */data/COM. example. hellojni/lib/libhello-jni.so at installation time * by the Package Manager. */static {system. loadlibrary ("hello-JNI") ;}@ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); system. out. println (resultret (3, 4); toast. maketext (getapplicationcontext (), stringfromjni () + "|" + resultret (3, 4), 1 ). show ();}}

This code is simple and the comments are clear. Here we only mention two points ::

Static {
System. loadlibrary ("hello-JNI ");
}


It indicates that the hello-JNI 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 your program has multiple classes and if hellojni is not the entry to your application, then hello-JNI (the complete name is libhello-jni.so) this library will be loaded when hellojni is used for the first time.

Public native string stringfromjni ();
Public native string unimplementedstringfromjni ();

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.

Then CD to the SRC of this project

PS E:\workspace\HelloJni\src> javah -jni com.example.hellojni.HelloJni

Javah-classpath bin-d jni com. example. hellojni. hellojni
But my error is always: the class file of 'com. example. hellojni. hellojni 'cannot be found.

As for many people, I keep failing in the bin. I am not clear about the reason. Ask my colleagues at work.

 

Continue ,. All right, in the project directory, a new JNI folder. The directory structure should be like this: androidmanifest. xml assets bin default. properties Gen res SRC

Okay,

javah -jni com.example.hellojni.HelloJni

After running the command, refresh your directory and run com_example_hellojni_hellojni. H. Drag the file into JNI. It seems that this file is useless.

Let's take a look at the content of com_example_hellojni_hellojni.h:

Com_example_hellojni_hellojni.h:

/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_example_hellojni_HelloJni */#ifndef _Included_com_example_hellojni_HelloJni#define _Included_com_example_hellojni_HelloJni#ifdef __cplusplusextern "C" {#endif/* * Class:     com_example_hellojni_HelloJni * Method:    stringFromJNI * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI  (JNIEnv *, jobject);/* * Class:     com_example_hellojni_HelloJni * Method:    resultRet * Signature: (II)I */JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_resultRet  (JNIEnv *, jobject, jint, jint);/* * Class:     com_example_hellojni_HelloJni * Method:    unimplementedStringFromJNI * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI  (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.

From the source code above, we can see that this function name is quite long .... However, it is still quite regular. It is named in the format of java_pacakege_class_mathod.

That is to say:

The stringfromjni () method in hello. Java corresponds to the java_com_example_hellojni_hellojni_stringfromjni () method in C/C ++.

The unimplementedstringfromjni () method in hellojni. Java corresponds to java_com_example_hellojni_hellojni_unimplementedstringfromjni () 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.

 

2.2 compile the corresponding. c file:

Hello-jni.c:

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */#include <string.h>#include <jni.h>/* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * *   apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java */jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,                                                  jobject thiz ){    return (*env)->NewStringUTF(env, "Hello from JNI !");}jint Java_com_example_hellojni_HelloJni_resultRet  (JNIEnv * env, jobject thiz, jint a, jint b){  jint x=0;  x=a+b; return x;  }

The hello-jni.c file has been compiled, now you can delete the com_example_hellojni_hellojni.h file, of course, keep it, but I am still used to clean up unnecessary files.

 

Compile the Android. mk File

Create an android. mk file in the JNI directory (that is, under the hello-jni.c directory at the same level), Android. mk
The file is an android makefile with the following content:

# Copyright (C) 2009 The Android Open Source Project## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at##      http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE    := hello-jniLOCAL_SRC_FILES := hello-jni.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: = hello-JNI

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 'libello-JNI ', the compiling system will not add any lib prefix or generate 'libello-JNI. so ', to support Android from the source code of the Android platform. MK file, if you do need to do so.

Local_src_files: = hello-jni.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.

 

CDWorkspace \ hellojni to the following and then ndk-build

Ps e: \ workspace \ hellojni> ndk-build
"Compile thumb: hello-JNI <= hello-jni.c
Sharedlibrary: libhello-jni.so
Install: libhello-jni.so => libs/armeabi/libhello-jni.so

Re-compile the hellojni project in eclipse to generate the APK

Eclipse refresh the hellojni project, re-compile to generate APK, libhello-jni.so shared library will be packaged together in the APK file.

Hey, there is a JNI initial test on Sun, next study

Related Article

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.