andoid 项目文件结构图
新建Hardcontrol.java
package com.thisway.hardlibrary;
public class HardControl {
public static native int ledCtrl(int which, int status);
public static native int ledOpen();
public static native void ledClose();
static {
try {
System.loadLibrary("hardcontrol");
} catch (Exception e) {
e.printStackTrace();
}
}
}
访问C库
1.修改build.gradle
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
新建hardcontrol.c文件
#include
#include
#include
#include
#if 0
typedef struct {
char *name; /* Java里调用的函数名 */
char *signature; /* JNI字段描述符, 用来表示Java里调用的函数的参数和返回值类型 */
void *fnPtr; /* C语言实现的本地函数 */
} JNINativeMethod;
#endif
jint ledOpen(JNIEnv *env, jclass cls)
{ __android_log_print(ANDROID_LOG_DEBUG, "JNIDemo", "native add …");
__android_log_print(ANDROID_LOG_DEBUG, "LEDDemo", "native ledOpen……");
return ;
}
void ledClose(JNIEnv *env, jclass cls)
{
__android_log_print(ANDROID_LOG_DEBUG, "LEDDemo", "native ledClose……");
}
jint ledCtrl(JNIEnv *env, jclass cls,jint which, jint status)
{
__android_log_print(ANDROID_LOG_DEBUG, "LEDDemo", "native ledCtrl: %d, %d",which, status);
return ;
}
static const JNINativeMethod methods[] = {
{"ledOpen", "()I", (void *)ledOpen},
{"ledClose", "()V", (void *)ledClose},
{"ledCtrl", "(II)I", (void *)ledCtrl},
};
/* System.loadLibrary */
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *jvm, void *reserved)
{
JNIEnv *env;
jclass cls;
if ((\*jvm)->GetEnv(jvm, (void \*\*)&env, JNI\_VERSION\_1\_4)) {
return JNI\_ERR; /\* JNI version not supported \*/
}
cls = (\*env)->FindClass(env, "com/thisway/hardlibrary/HardControl");
if (cls == NULL) {
return JNI\_ERR;
}
/\* 2. map hello java<-->c c\_hello \*/
if((\*env)->RegisterNatives(env, cls, methods, sizeof(methods) / sizeof(methods\[\])) < )
return JNI\_ERR;
return JNI\_VERSION\_1\_4;
}
2.编译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
**
3.在app/libs下建armeabi子目录,放入so文件
在4412开发板上运行,点相应按钮后会有调试信息打印
手机扫一扫
移动阅读更方便
你可能感兴趣的文章