java爲了調用底層驅動函數,須要調用外部的C/C++代碼,java提供了JNI接口:java
而後將C代碼編譯成庫(windows下 .dll / android環境下 .so)linux
arm-linux-gcc -fPIC -shared hardcontrol.c -o libhardcontrol.so -I /usr/lib/jvm/java-1.7.0-openjdk-amd64/include -nostdlib /work/android-5.0.2/prebuilts/ndk/9/platforms/android-19/arch-arm/usr/lib/libc.so -I /work/android-5.0.2/prebuilts/ndk/9/platforms/android-19/arch-arm/usr/include /work/android-5.0.2/prebuilts/ndk/9/platforms/android-19/arch-arm/usr/lib/liblog.soandroid
arm-linux-gcc -fPIC -shared jni_test.c -o libtesthw.so -I /usr/lib/jvm/java-1.7.0-openjdk-amd64/include -nostdlib /work/android-5.0.2/prebuiltoid-19/arch-arm/usr/lib/libc.ss/ndk/9/platforms/android-19/arch-arm/usr/lib/libc.so -I /work/android-5.0.2/prebuilts/ndk/9/pla-5.0.2/prebuilts/ndk/9/platfortforms/android-19/arch-arm/usr/include /work/android-5.0.2/prebuilts/ndk/9/platforms/android-19/arch-arm/usr/lib/liblog.so -nostdlib /work/android-5.0.2/prebuilts/ndk/9/platforms/android-19/arch-arm/usr/lib/libm.sowindows
而後將生成的動態連接庫放到android studio工程的app/lib目錄下:app
新建armeabi子目錄,放入.so文件jvm
static{
System.loadLibrary("hardcontrol"); //指定動態庫
};
修改app路徑下的build.gradle:函數
加上gradle
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
1 #include <stdio.h> 2 #include <jni.h> 3 4 jint ledOpen(JNIEnv *env, jobject cls) 5 { 6 printf("all led opened\n"); 7 return 0; 8 } 9 10 jint ledCtrl(JNIEnv *env, jobject cls, jint which, jint status) 11 { 12 printf("status of %d is %d \n", which, status); 13 return 0; 14 } 15 16 void ledClose(JNIEnv *env, jobject cls) 17 { 18 printf("all led closed\n"); 19 } 20 21 static JNINativeMethod gMethods[] ={ 22 {"ledCtrl", "(II)I", (void *)ledCtrl}, 23 {"ledOpen", "()I", (void *)ledOpen}, 24 {"ledClose", "()V", (void *)ledClose}, 25 }; 26 27 28 JNIEXPORT jint JNICALL 29 JNI_OnLoad(JavaVM *jvm, void *reserved) 30 { 31 JNIEnv *env; //struct JNINativeInterface_ * 32 33 if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_4)) { 34 return -1; 35 } 36 jclass cls = (*env)->FindClass(env, "com/example/hardlibrary/HardControl"); //java裏面類的路徑 37 if (cls == NULL) { 38 return -1; 39 } 40 if((*env)->RegisterNatives(env,cls, gMethods, sizeof(gMethods)/sizeof(gMethods[0]))< 0) { 41 return -1; 42 } 43 44 return JNI_VERSION_1_4; 45 }