Using the NDK JNI development project above Android Studio

Source: Internet
Author: User

Ps: Recently more busy, so. More than a few blog updates are summed up. By the way to despise some programmer copy on-line article, and do not own to carry out the relevant practice verification. Make the blog above the Web a stereotyped, As long as the person who originally wrote the blog stepped on the pit behind the pit. For this kind of non-actual test on the big copy of the people deeply despise

OK then let's get to the point of today, that is, how to use and configure the NDK correctly in Android Studio. If you have a child shoe that is not known to JNI, it is recommended that you study the JNI technology first to see this blog post.

Reprint please indicate source: http://blog.csdn.net/unreliable_narrator?viewmode=contents

The usual, let's look at the effect of the implementation: Click the button will invoke the C code method, where the C code method will return a string, we will show this string.


Preparation : First, let's look at what is required for JNI development:Android studio1.51 (official version),android-ndk-r11b (/HTTP// www.androiddevtools.cn/), a programmer . Preparation is to download the NDK to configure the Ndk-home (method and Java-home configuration of the same, so do not repeat, not self-Baidu, it is said that can not be configured (⊙﹏⊙)).

Start the tutorial below

1. First use Android studio to create an Android project. and associated with the NDK. There are two ways of associating it in a project setup , and the other is in the engineering catalog the path of the NDK is configured in Local.properties , and one of the two options is as follows:

(Programme i)

(option 2)

         2. open   grade.properties   file, added at the end: android.usedeprecatedndk=true.

3. Then configure the NDK parameters in the module's build.gradle file.       

Apply plugin: ' Com.android.application ' android {    compilesdkversion    buildtoolsversion "23.0.3"    defaultconfig {        ApplicationID "Com.dapeng.ndkdemo"        minsdkversion        targetsdkversion        Versioncode 1        versionname "1.0"        ndk {            modulename "myjnilibname"            //generated so name (can be specified by yourself)            Abifilters "Armeabi", "armeabi-v7a", "x86"    //outputs specify so libraries under three ABI architectures. Currently optional (the default is select All).            //ldlibs "Log"                                //If you want to use log, add this        }    }    buildtypes {        release {            minifyenabled false            proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '}}    } dependencies {    Compile filetree (dir: ' Libs ', include: [' *.jar '])    testcompile ' junit:junit:4.12    ' Compile ' com.android.support:appcompat-v7:23.3.0 '}

4. Create a class to write a method that calls C code. Then rebuild the project. The name of the loading library is the one we configured in buil.gradle .ModuleNamethe method of calling C code must be decorated with native . (Note that it is not possible to write Chinese in it, including comments, otherwise the generated header file will report an error: encoding GBK non-mapped characters )

public class Jniutils {    static {        system.loadlibrary ("Myjnilibname");       }    Public native String GETSTRINGFROMC (); }
5.after the project build is complete, enter the Debug folder as shown to see if the. class file that corresponds to the classes we wrote is generated. The directory is as follows .


6. If the class file is generated correctly, then the header file is generated. Open Android Studio terminal(Android Studio comes with the console, in the win10 above needs to be set to normal input, the specific way to ask Niang) or the cmd console. Use the JDK build tool to generate the header file. CD to our module's Java folder and then use Javah-jni + to call the full path name of the class of C code .It is best to look at the path under which the build was compiled. After the build, you can see the. h Format header file in the project directory. (Look closely at the path I posted, the app is the module name)


7. Click Project new-folder-jnifolder to generate the Jni folder ( You can also create the Jni folder yourself in the Java package's sibling directory ), Jni folder Create an arbitrary name and a file that ends in the . C format . The . The contents of the H header file are copied into the. c file and edited.

/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Com_dapeng_ndkdemo_jniutils */#ifndef _included_com_dapeng_ndkdemo_jniutils#define _included_com_dapeng_ndkdemo_jniutils#ifdef __ Cplusplusextern "C" {#endif */* Class:     com_dapeng_ndkdemo_jniutils * Method:    GETSTRINGFROMC * Signature: () ljava/lang/string; */jniexport jstring jnicall JAVA_COM_DAPENG_NDKDEMO_JNIUTILS_GETSTRINGFROMC        (jnienv *env, Jobject obj) {    Return (*ENV)->newstringutf (env, "Hello Java from C");} ; #ifdef __cplusplus} #endif #endif
8.Finally, we can call the C code method through the written method inside the jniutils . That's it. Now that all the code has been written

public class Mainactivity extends Appcompatactivity {    private TextView mtextview;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Mtextview = (TextView) Findviewbyid (r.id.tv);        Findviewbyid (R.ID.BTN). Setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View V {                Mtextview.settext (new Jniutils (). GETSTRINGFROMC ());}            }        );}    }

9. Click Rebuild Project, and after the project build is finished, go to the Buil intermediates folder to see if the NDK folder is generated, and then see if there are any. so files in the Ndk folder. If there is, it means the Gaocheng. Plase enjory it.



Using the NDK JNI development project above Android Studio

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.