Android studio ndk Development
Create a project
Create an android studio project using the wizard
Create a Test class
package cn.edu.zafu.jnidemo;public class Test { static { System.loadLibrary("Test"); } public native String getName();}
Make project
Build-> make project
Generate header files
Open the terminal in as and enter the main directory to generate the header file
cd app/src/mainjavah -d jni -classpath "D:\Program Files\adt-bundle-windows-x64-20140702\sdk\platforms\android-21\android.jar;..\..\build\intermediates\classes\debug" cn.edu.zafu.jnidemo.Test
The directory contains spaces. Please use double quotation marks to include
Then, the header file is generated in the jni directory. copy the file and change it to. c. The implementation content is as follows:
#include
JNIEXPORT jstring JNICALL Java_cn_edu_zafu_jnidemo_Test_getName(JNIEnv * env, jobject jObj){ jstring str = (*env)->NewStringUTF(env, "HelloWorld from JNI !"); return str;}
Create a new util. c In the jni directory (other names are also allowed). The content is blank; otherwise, an error is reported.
Configure the ndk directory
Open local. properties and add the ndk directory.
sdk.dir=D\:\\Program Files\\adt-bundle-windows-x64-20140702\\sdkndk.dir=D\:\\android-ndk-r10b
Configure build. gradle
Open the file and add the ndk configuration in defaultConfig.
defaultConfig { ndk { moduleName "Test" } }
Add the following configuration
productFlavors { x86 { versionCode Integer.parseInt("6" + defaultConfig.versionCode) ndk { abiFilter "x86" } } mips { versionCode Integer.parseInt("4" + defaultConfig.versionCode) ndk { abiFilter "mips" } } armv7 { versionCode Integer.parseInt("2" + defaultConfig.versionCode) ndk { abiFilter "armeabi-v7a" } } arm { versionCode Integer.parseInt("1" + defaultConfig.versionCode) ndk { abiFilters "armeabi", "armeabi-v7a" } } fat }
Recompile
Call
package cn.edu.zafu.jnidemo;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.widget.Toast;public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Test t=new Test(); Toast.makeText(this,t.getName(),Toast.LENGTH_LONG).show(); }}