Android NDK Development

Source: Internet
Author: User

I do not have any basis for the C + +, although the University Middle School a semester of C but all return to the teacher. This article is I do an NDK project accumulated knowledge, can be said to be a small white hands-on articles, so master please take a detour by themselves.

1. Preparation

To do NDK development is very important to note the development environment and development version of (personally think). I am using Eclipse (Luna 4.4.0), NDK version R10, should be in the <=R6 version of the NDK also need to install Cygwin (this is not discussed here, online a lot of information), attached to the NDK download link convenient can not flip the wall of friends, 32-bit, 64-bit, The website cannot be accessed, but it can be downloaded directly with the download link.

Once the NDK is installed, it needs to be configured on eclipse.

1, windows-preferences-android-ndk-ndklocation Select the NDK installation directory

2. Configure the builder environment to right--properties-builder-new-program the following configuration in the pop-up window that is required for the NDK development project

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/6B/80/wKioL1Uva7bxkgyqAAHHkSQdv6o361.jpg "style=" float: none; "title=" 1.png "alt=" Wkiol1uva7bxkgyqaahhksqdv6o361.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/6B/84/wKiom1UvamKgeEteAAE299U2L3w010.jpg "style=" float: none; "title=" 2.png "alt=" Wkiom1uvamkgeeteaae299u2l3w010.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/6B/80/wKioL1Uva7eRmrMdAAIIeisqxW0452.jpg "style=" float: none; "title=" 3.png "alt=" Wkiol1uva7ermrmdaaiieisqxw0452.jpg "/>

3. Right-click Project Project Android Tools-add Native support

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/6B/80/wKioL1UvbF_Cvl6KAAAst-L9hxw144.jpg "title=" 4.jpg " alt= "Wkiol1uvbf_cvl6kaaast-l9hxw144.jpg"/>

The JNI directory appears and Android.mk,xx.cpp adds success. The NDK can be developed.


2. Java calls methods in C + +.

For example, get a string from a C + + file and print

In activity Class A:

static{system.loadlibrary ("xx");//xx is the Local_module field in the Android.mk file}//must be the same as the method name in the NDK native String getString ()    ;//onclick method public void Click (View v) {String str = getString (); System.out.println ("Invoke Method in Jni:" +str);}

In the Ndk.cpp

#include <jni.h> #include <string.h>/*** extern "C" is to be added, the test does not add the method call is unsuccessful, did not find the answer, there is know why please * inform, The method name must be Java_ the package name _ Class Name _ Method name according to JNI specification, and must be separated by ' _ '.    */extern "C" jstring java_com_test_ndk_a_getstring (jnienv* env,jobject thiz) {jstring str;    In c is called by (*env), most of the online blog document is also the case.    str = ENV->NEWSTRINGUTF ("Hello World");//cannot use Chinese, otherwise it will error. return str;}

You can see the effect by running the project.

3. Calling Java methods in C + +

In the CLASSB

static{system.loadlibrary ("NDK");    public native void Loadjavamethod ();p ublic void F1 () {String str;    str = "Hello world from Java"; System.out.println (str);}    Public String F2 () {string str;    str = "F2:hello world from Java";    System.out.println (str); return str;} public void F3 (String str,int i) {System.out.println ("F3 content is:" +str+ ", the number is:" +i);}

In the Ndk.cpp

#include  <jni.h> #include <string.h>extern  "C"  void java_com_test_ndk_b_ Loadjavamethod (jnienv *env,jobject thiz) {    //Call no parameter no return value method      jclass cls = env->getobjectclass (Thiz);     //getmethodid ("Jclass object "," Method Name "," method parameter ")     jmethodid mid = env->getmethodid (CLS," F1 "," () V ");     if (mid != null) { env->callvoidmethod (Thiz,mID);     }    //call has parameter no return worthwhile method      //parameter types in addition to the basic data types, others need to follow this format   &NBSP;&NBSP;&NBSP;&NBSP;//L Package Name/class name;   package name used/split, must be; end      //for details, please refer to this article            jclass cls = env->getobjectclass (Thiz) ;     jmethodid mid = env->getmethodid (CLS, "F3", "(ljava/lang/string;i) V") ;     jstring&nbSp;content = env->newstringutf ("hehe");    jint i = 10;     if (mid != null) { env->callvoidmethod (thiz,mid,content,i);     }    //call a method that has a return value of no argument     jclass cls = env-> Getobjectclass (Thiz);     jmethodid mid = env->getmethodid (CLS, "F2", "() ljava/lang/string; ");      if (mid != null) { env->callobjectmethod (Thiz,mID);     }    //calls methods in other classes to assume that there is a student class, if you want to use an inner class A in the student class, format     / /com/test/ndk/student$a    jclass stu = env->findclass ("com/test/ndk/ Student ");     //instantiation method of non-parametric construction     jobject stuObj = env-> NewObject (Stu,env->getmethodid (Stu, "<init>", "() V"));     jmethodid getnameid& nbSp;= env->getmethodid (Stu, "GetName", "() V");     if (Getnameid !=null) {env-> Callvoidmethod (Stuobj,getnameid);     }}

4. Call a third-party so file in your own so file

This is generally because the methods in the third-party C/s + + are not written in accordance with the JNI specification, and need to be repackaged and used, of course, if a third party documentation is available.

Configure third-party so files to pre-compile environment

Create a new prebuilt folder under the project's JNI file (name optional) put the third party's so file inside such as libthird.so, and then create a new Androdid.mk file under this folder, the file content is

Local_path: = $ (call My-dir) include $ (clear_vars) Local_module: = libthirdlocal_src_files: = Libthird.soinclude $ (PREBUI Lt_shared_library)

Open the Android.mk file under JNI and add the following fields

Local_path: = $ (call My-dir) include $ (clear_vars) Local_module: = ndklocal_src_files: = ndk.cpp# name and local_module definition in third party MK The same name as local_shared_libraries: = Libthirdinclude $ (build_shared_library) #添加路径include $ (Local_path)/prebuilt/ Android.mk

After the configuration is complete, the third party's so file can be seen in the Libs\armeabi directory of the project, and note that the third party's so file cannot be placed directly under this directory. Otherwise, it will be deleted when Builde.

Assume that there is a method in a third-party C + + file

extern "C" methods in third-party packages must also be added when testing, if the method call is not added successfully, but this is not limited to//to a third party, pending resolution extern "C" int F1 () {return 101;}

Calling a third-party method in your own C + + file

#include <jni.h> #include <dlfcn.h> #include <fcntl.h>void *filehandle = null;jstring (*F1) () =null;    extern "C" Jint java_com_test_ndk_classa_f1 (jnienv * env,jobject thiz) {jint i;    FileHandle = Dlopen ("/data/data/com.fly.ndk2/lib/libndk.so", Rtld_lazy);    if (filehandle) {f1 = (int (*) ()) Dlsym (FileHandle, "F1");        } if (f1) {i = F1 ();    Dlclose (filehandle); filehandle = NULL; } return i;}

In addition to the above content does not involve the real C + + programming, the JNI development of some of the knowledge points are involved, only a few of the knowledge of the introduction, in the case of a complete lack of understanding of C/S programming, took 2 days to accumulate the above knowledge. If you need more in-depth learning, you will need to learn the syntax and compile.

The above code and operations are not necessarily valid in other environments, remember.

This article is from the "Fly" blog, please be sure to keep this source http://fujian0910.blog.51cto.com/1706151/1633522

Android NDK Development

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.