Android JNI configuration and Getting Started

Source: Internet
Author: User

Android JNI configuration and Getting Started


JNI is a technique that can call C + + code in Java, which means that it can be developed on Android using C + +. However, it is not possible to develop Android apps in pure C + +, because these C + + code is called through Java-defined interfaces.

I experimented with Jni on Android using Ndk-r10, no cygin, and another tutorial when using the lower version of the NDK.


NDK installation and how to configure the NDK in ADT

You can go to the Android Developer website to download the latest NDK toolkit, download it and unzip it to a list of easy-to-find directories, such as we unzipped to C: \ So the NDK is installed in the C:\android-ndk-r10 directory.


To use the NDK in your Android project also requires configuration, the configuration method is very simple:

In Eclipse ADT, open the WINDOW->PREFERENCE->ANDORID->NDK and fill in the NDK location with the directory where you installed the NDK, which is the C:\android-ndk-r10 above. Now ADT can automatically invoke the tools associated with building the NDK project based on the NDK path you provide.


Try the first NDK program

1. First create an Android project named Ndktest in Eclipse ADT.

2. In ADT you want to use the NDK's engineering catalog (here is the Ndktest directory), right-click on Android tools->add Native support ...


In the popup dialog box, fill in the file name of the binary link library you are about to generate, here we take hello.so as an example


Then click Finish, and wait a moment, and you'll find a folder called JNI in your project directory.


3. Now it's time to start writing the C + + code that finally worked that part, which is written in Hello.cpp (the file name of the CPP file is the same as the filename of the. So link library you just created), and we write the following code in the CPP:

-----------------------------------Start-------------------------------------------

#include <jni.h>
#include <string.h>


The method defined by C + + must be java+ package name +activity name + your function name, each part with an underscore _ to connect,
And the parameters are fixed. Therefore, the fixed format for defining C + + functions is:
Java_packagename_activityname_function (jnienv* env, Jobject obj) {...}
//
Here the extern "C" is to prevent C + + compile binary link library when the function is renamed, in fact, add does not affect the implementation of the code to run the effect,
But if your program because Java.lang.UnsatisfiedLinkError:Native method not found this
If you fail, you should add it.
extern "C" jstring Java_com_example_hellojni_mainactivity_hello (jnienv* env, Jobject obj) {
return Env->newstringutf ("Hello JNI.");
}

---------------------------------------End-------------------------------------------------------

The comments in the code have been explained very clearly, and you have defined C + + functions to be named in a fixed format.

ADT automatically calls Ndk-build when you click the Run button to run your app to compile our C/C + + code.

4. In order to invoke our write-C + + code, we need to add the following code snippet to the Java source:

-------------------------------Start---------------------------------------------------------------

public class Mainactivity extends Activity {


Because the static block is loaded more than any other code, here we import our dynamic link library
Remember to let yourself fill in the. so file name, here you write the file name can be imported
static {
System.loadlibrary ("Hello");
}


To define an empty method in Java code like this, use your own custom C + + function.
The return value is the same as the type returned by the C + + function that you defined earlier, the name of the function and the C/
The last part is okay, because the last part is the name of the function.
Public native String hello ();


@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TextView TV = (TextView) Findviewbyid (r.id.tv);
Tv.settext (hello ());
}


}

-------------------------------End---------------------------------------------------------------

Post-run Effects:


Note that the CPP file is easy to compile error can check whether these places are configured well


1. Project Right-click properties->c/c++ Build Building Settings Remove the Use default Build command and enter ${ndkroot}/ndk-build.cmd




2. Click on environment in the C + + build, click Add ... Add environment variable Ndkroot, the value of the NDK root directory

3. Re-compile, the problem is solved!

Run-time crash, encountered Java.lang.UnsatisfiedLinkError:stringFromJNI error, Workaround: add extern "C" modifier before function definition in C + + file

extern"C"{Jniexport jstring jnicall java_com_shamoo_activity_testactivity_stringfromjni (jnienv*env,    Jobject thiz);} Jniexport jstring jnicall Java_com_shamoo_activity_testactivity_stringfromjni (jnienv*env,    Jobject thiz) {  returnEnv->newstringutf ("Hello jni");}
The reason is that with extern "C" adornments, the compiler compiles and connects in C language. In the C language, after the function is compiled, the function name differs from the C + + function, such as foo (int x, int y), C may be compiled into a _foo name, and C + + because it supports overloading, it compiles the function name that _foo_int_int the parameter with the image. If you are compiling the C language, calling the Foo function will not find the function name of _foo and the function name cannot be found. So add the extern "C" modifier.  

Android JNI configuration and Getting Started

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.