Environment:
Android Studio 1.1.0
ndk-r10d
1. New Project---"Package name: COM.MXL.AZ.NDK
To create a new class that contains the native method: Jnioperation.class
Public class jnioperation { publicstaticnative String getString (); Public native int Add (intint b);}
2. Then use the Javah command to generate the. h file
Open "small black box", enter the project directory of .../app/build/intermediates/classes/debug/
Javah-jni com.mxl.az.ndk.JniOperation
After the command is executed, the. h file is generated in the debug directory
3. Create a new JNI folder in the Src/main directory
Copy the. h file to the Jni folder
4. Create a new Main.c,include-->.h file and implement the two methods
#include"Com_mxl_az_ndk_jnioperation.h"#include<android/log.h>#defineLog_tag "Hellojni"#defineLogi (...) __android_log_print (android_log_info,log_tag,__va_args__)#defineLOGE (...) __android_log_print (android_log_error,log_tag,__va_args__)jniexport jstring jnicall java_com_mxl_az_ndk_jnioperation_getstring (jnienv*env, Jclass CLA) { inti; intSize =4; for(i=0; i<size; i++) {Logi ("MXL"); } return(*env)->newstringutf (env,"results of the JNI operation:");} Jniexport jint jnicall java_com_mxl_az_ndk_jnioperation_add (jnienv*env, Jobject obj, jint A, jint b) { returnA +b;}
5. Configure the NDK path in local.properties
ndk.dir=/users/mxl/android/android-ndk-r10d
6. Configure the NDK in the Build.gradle file
Defaultconfig {minsdkversion8targetsdkversion AVersioncode1Versionname"1.0"NDK {abifilter"Armeabi"ModuleName"Hellojni"Ldlibs"Log","Z","m","Jnigraphics","Android" } }
7, load the library in the activity, run
1 Public classMainactivityextendsactionbaractivity {2 3 Static {4System.loadlibrary ("Hellojni");5 }6 7 PrivateTextView TV;8 9 @OverrideTen protected voidonCreate (Bundle savedinstancestate) { One Super. OnCreate (savedinstancestate); A Setcontentview (r.layout.activity_main); - -TV =(TextView) Findviewbyid (r.id.tv); theJnioperation jnioperation =Newjnioperation (); -Tv.settext (jnioperation.getstring () + Jnioperation.add (2,8)); - } -}
An introduction to the development of Android Studio NDK