java为了调用底层驱动函数,需要调用外部的C/C++代码,java提供了JNI接口:
然后将C代码编译成库(windows下 .dll / android环境下 .so)
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.so
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.so
然后将生成的动态链接库放到android studio工程的app/lib目录下:
新建armeabi子目录,放入.so文件
static{
System.loadLibrary("hardcontrol"); //指定动态库
};
修改app路径下的build.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 }