Android Studio NDK learns to accept Java incoming strings

Source: Internet
Author: User
Tags jcenter

This blog is based on Android Studio 1.3 preview version, and by default you have installed the Android SDK, Android NDK.

Create a new project with Android studio called prompt, whose directory structure is as follows:

├──prompt.iml

├──app

│├──app.iml

│├──build

│├──build.gradle

│├──libs

│├──proguard-rules.pro

│└──src

├──build

│└──intermediates

├──build.gradle

├──gradle

│└──wrapper

├──gradle.properties

├──gradlew

├──gradlew.bat

├──local.properties

└──settings.gradle

To switch to Android view, the following directory is visible:

The first step is to write the JNI code:

1, create a new JNI folder, under the Jni folder created Logger.h, used to print the output log, the contents are as follows:

#ifndef Prompt_logger_h_h#definePrompt_logger_h_h#include<jni.h>#include<android/log.h>/** * Define log label*/#defineTAG "Jni_logger"/** * Define info Info*/#defineLogi (...) __android_log_print (Android_log_info, TAG, __va_args__)/** * Define debug information*/#defineLOGD (...) __android_log_print (Android_log_debug, TAG, __va_args__)/** * Define error information*/#defineLOGE (...) __android_log_print (Android_log_error, TAG, __va_args__)#endif //Prompt_logger_h_h

2, then create PROMPT_JNI.C is mainly used to register bound Java functions and native functions, and Java functions in C, the corresponding function of the specific implementation, the contents are as follows:

#include"Logger.h"#ifndef NULL#defineNULL ((void *) 0)#endif/** * Get the size of the array*/#defineNelem (x) ((int) (sizeof (x)/sizeof ((x) [0]))#defineJnireg_class "Com/ndk/clarck/prompt/mainactivity"/** * Return string*/jniexport jstring jnicall native_getline (jnienv*env, Jobject obj, jstring prompt) {    Charoutbuf[ -]; intLen = (*env)getstringlength (env, prompt); (*ENV)->getstringutfregion (env, prompt,0, Len, outbuf); return(*env)Newstringutf (env, OUTBUF);}/** * Java and JNI function bindings*/StaticJninativemethod method_table[] = {        {"GetLine","(ljava/lang/string;) ljava/lang/string;", (void*) Native_getline},};/** * Register native method into Java*/Static intRegisternativemethods (JNIEnv *env,Const Char*ClassName, Jninativemethod* Gmethods,intnummethods)    {Jclass clazz; Clazz= (*env)Findclass (env, className); if(Clazz = =NULL) {        returnJni_false; }    if((*env)->registernatives (env, Clazz, Gmethods, Nummethods) <0)    {        returnJni_false; }    returnjni_true;}/** * Call registration Method*/intRegister_ndk_load (JNIENV *env) {    returnregisternativemethods (env, Jnireg_class, method_table, Nelem (method_table));} Jniexport jint jni_onload (JAVAVM*VM,void*reserved) {jnienv* env =NULL; Jint result= -1; if((*VM)->getenv (VM, (void* *) &env, jni_version_1_4)! =JNI_OK) {        returnresult;    } register_ndk_load (env); returnjni_version_1_4;}

3. The Java layer is called as follows:

 Packagecom.ndk.clarck.prompt;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); String GetLine= GetLine ("Type a line:"); LOG.D ("Test", "GetLine:" +getLine); }     Public nativestring GetLine (String prompt); Static{system.loadlibrary ("Prompt_jni"); }}

The second step is to configure the following environment to execute the compile command:

1. Configure the SDK and NDK path in Local.properties as follows:

Sdk.dir=xxxx

Ndk.dir=xxx

2. Open Gradle-wrapper.properties, modify its configuration to use Gradle 2.5来 compilation (detail reference: http://www.cnblogs.com/tanlon/p/4731283.html):

#Mon 20:34:50 HKTdistributionbase=gradle_user_homedistributionpath=wrapper/  Distszipstorebase=gradle_user_homezipstorepath=wrapper/distsdistributionurl  =https\://services.gradle.org/distributions/gradle-2.5-all.zip

3. Configure Build.gradle under Project, with the following contents:

// top-level build file where can add configuration options common to all sub-projects/modules. Buildscript {    repositories {        jcenter ()    }    dependencies {        ' com.android.tools.build: gradle-experimental:0.2.0'        //  Note:do not place your application dependencies here; they Belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter ()    }}

4, configure the module below the Build.gradle, its contents are as follows:

Apply plugin: ' Com.android.Model. Application ' model {android {compilesdkversion= 21buildtoolsversion= "22.0.1"Defaultconfig.with {ApplicationID= "Com.ndk.clarck.prompt"Minsdkversion.apilevel= 15Targetsdkversion.apilevel= 21}} android.ndk {ModuleName= "Prompt_jni"Ldlibs+ = ["Log"]} android.buildtypes {release {minifyenabled=falseProguardfiles+ = file (' Proguard-rules.pro ')}} android.productflavors {Create ("ARM7") {ndk.abifilters+ = "armeabi-v7a"} Create ("ARM8") {ndk.abifilters+ = "arm64-v8a"} Create ("X86-32") {ndk.abifilters+ = "x86"        }        //For detailed abifilter descriptions, refer to "Supported ABIs" @// https://developer.android.com/ndk/guides/abis.html#sa//build one including all CPU architecturesCreate ("All")    }}

5, execute Build->make Project, get the following output:

1:27:09 pm Executing tasks: [: App:compilealldebugsources,: app:compilealldebugandroidtestsources]1:27:10 pm Gradle build finished in 779ms

6. Run the project by executing run.

Experience:

1, Encounter Gradle sync failed:Cause:org.gradle.api.internal.ExtensibleDynamicObject This error solution:

The module under the Build.gradle All compilation parameters are assigned to the use of xxx = xxx this way, and can not use xxx xxx this way of assignment

2. Android Studio Gradle compilation is really much more convenient than using Android makefile in Eclipse.

Android Studio NDK learns to accept Java incoming strings

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.