Android Studio JNI development (2) - Java calls C method to output string
-
Create a new Android project
-
Configure the ndk path in the local.properties file
ndk.dir=D\:\\Android\\SDK\\ndk-bundle
-
File ----> Project Structure ----> SDK Lcation配置Android NDK location。
-
The gradle.properties file configuration is compatible with the old ndk
android.useDeprecatedNdk=true
5. Create a new Java JNI class MyJni.java, and write the JNI native method.
package com.csu.ndkdemo;
public class MyJNI {
public native String sayHello();
}
- To generate the header file, enter the project path NdkDemo\app\src\main\java with cmd, and execute the command to generate the .h header file.
javah -classpath . -jni com.csu.ndkdemo.MyJNI
Generate a .h header file in the same directory as the MyJNI.java file (main\java\com.csu.ndkdemo) com_csu_ndkdemo_MyJNI.h
.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_csu_ndkdemo_MyJNI */
#ifndef _Included_com_csu_ndkdemo_MyJNI
#define _Included_com_csu_ndkdemo_MyJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_csu_ndkdemo_MyJNI
* Method: sayHello
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_csu_ndkdemo_MyJNI_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
- Create a new jni directory in the same directory as java under main, copy the .h file generated by step6 to the jni directory, and then create a new Hello.c file to implement the method in the .h file.
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
JNIEXPORT jstring JNICALL Java_com_csu_ndkdemo_MyJNI_sayHello(JNIEnv *env, jobject thiz) {
return (*env)->NewStringUTF(env, "I`m Str from jni libs!");
}
- Create a new Android.mk file under the jni directory.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Hello
LOCAL_SRC_FILES := Hello.c
APP_ABI := all
include $(BUILD_SHARED_LIBRARY)
- Enter the project path NdkDemo\app\src\main\java with cmd, execute the command to compile and generate the .so file.
ndk-build
Two folders libs and obj will be generated in the same directory of jni.
- Copy the contents of the libs folder to the libs directory under the module project name.
- Add a reference to libs in the android{} node of the module's build.gradle file:
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
- The .so file is loaded in the JNI Java file MyJni.java.
package com.csu.ndkdemo;
public class MyJNI {
static {
System.loadLibrary("Hello");
}
public native String sayHello();
}
- Call the JNI method in the Activity and print out the string in C.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 调用JNI方法
String rs = new MyJNI().sayHello();
Log.i("MainActivity", "onCreate: " + rs);
}
}