基于Android studio3.6的JNI教程之helloworld思路详解
jdk环境变量配置:
path中增加下面2个路径,也就是androidstudio的路径,android有自带的jdk。
E:\Android\AndroidStudio\jre\bin E:\Android\AndroidStudio\bin
新建工程:
一定要选择Nativec++类型,最后要选c++11支持。
SDK设置:
File->Settings
File->ProjectStructure
首先确定工程的目录结构,然后尝试运行一下工程,使用模拟器,确保工程没问题,
在MainActivity的同级目录,新建一个hello.java,然后做一个简单的实现,
packagecom.example.myapplication; publicclasshello{ publicnativeintadd(inti,intj); }
使用androidstudio自带的Terminal进入该hello.java所在目录,执行,
javachello.java
Terminal下回到app/src/main所在目录,执行,
javah-djni-classpath./javacom.example.myapplication.hello
此时,会在main目录下面生成一个和cpp,java同级的目录jni。
在该目录结构里面新建hello.cpp。
将com_example_myapplication_hello.h中的内容复制进hello.cpp中,并且进行方法的实现,
#include/*Headerforclasscom_example_myapplication_hello*/ #ifndef_Included_com_example_myapplication_hello #define_Included_com_example_myapplication_hello #ifdef__cplusplus extern"C"{ #endif /* *Class:com_example_myapplication_hello *Method:add *Signature:(II)I */ #include"com_example_myapplication_hello.h" JNIEXPORTjintJNICALLJava_com_example_myapplication_hello_add (JNIEnv*,jobject,jinti,jintj){returni+j;} #ifdef__cplusplus } #endif #endif
将com_example_myapplication_hello.h,hello.cpp这连个文件复制到cpp所在的目录,
然后修改CMakeLists.txt,增加,
add_library(#Setsthenameofthelibrary. hello #Setsthelibraryasasharedlibrary. SHARED #Providesarelativepathtoyoursourcefile(s). hello.cpp)
修改target_link_libraries如下,
target_link_libraries(#Specifiesthetargetlibrary. native-lib hello #Linksthetargetlibrarytotheloglibrary #includedintheNDK. ${log-lib})
修改hello.java的调用方式,
packagecom.example.myapplication; publicclasshello{ static{ System.loadLibrary("hello"); } publicnativeintadd(inti,intj); }
修改MainActivity.java中的onCreate函数,
protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Exampleofacalltoanativemethod TextViewtv=findViewById(R.id.sample_text); //tv.setText(stringFromJNI()); tv.setText("hello9+10="+newhello().add(9,10)); }
然后,rebuildproject,没有错误后,然后runapp。
最终程序整体目录结构,以及运行效果,
JNI的整体流程思路:
Java先定义一个类,类中定义一个需要c++来实现的方法.通过javah生成需要c++实现的.h的c++头文件实现.h的c++头文件中定义的方法Cmake编译运行
总结
到此这篇关于基于Androidstudio3.6的JNI教程之helloworld思路详解的文章就介绍到这了,更多相关androidstudioJNIhelloworld内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。