Andoid之硬件访问服务1(让Andoid应用程序访问c库)
Posted CZM&
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Andoid之硬件访问服务1(让Andoid应用程序访问c库)相关的知识,希望对你有一定的参考价值。
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 <jni.h> /* /usr/lib/jvm/java-1.7.0-openjdk-amd64/include/ */ #include <stdio.h> #include <stdlib.h> #include <android/log.h> /* android log*/ #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 0; } 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 0; } 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[0])) < 0) 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开发板上运行,点相应按钮后会有调试信息打印
以上是关于Andoid之硬件访问服务1(让Andoid应用程序访问c库)的主要内容,如果未能解决你的问题,请参考以下文章
Andoid 9.0 程序更新后不能弹出“打开完成”界面,或点击“打开”不能启动程序