进程保活,热修复,硬件接入等等都需要底层的支持,而底层代码是 C 、C++ 写的,那么在 Android 中怎么调用底层的库呢?这里就需要了解 JNI 技术。 Android Studio 出来两年多了,网上针对 AS 开发 JNI 工程资源比较少,针对于此,我特意写下本篇博客,希望能对大家有所帮助。 配置环境 捡代码论坛(bbs.jiandaima.com)整理提供 下载NDK 请点击这里 ,并进行环境配置,如图: 
项目关联NDK ,具体操作如图:
右键你的工程项目,选择 【Open Module Settings】 
在 【Android NDK location】配置 NDK 的按着目录: 
最后在 项目根目录 【gradle.properties】 下加上:
- android.useDeprecatedNdk=true
复制代码
如图: 
JNI实现 新建 JNI_DEMO 项目,完成以上的配置工作。我的项目路径为:D:\Android_Study_Demos\JNI_DEMO 生成 .h 文件
新建TestJNI类
- public class TestJNI {
-
- public native String HelloWord(String str);
-
- }
复制代码

在cmd命令下面,cd到java目录,输入javah -jni com.github.jni_demo.TestJNI命令,生成 .h 文件: 
注意:com.github.jni_demo.TestJNI 不能 cd com , cd github……否则编译不成功。 你会发现在你的java路劲下生成了com_github_jni_demo_TestJNI.h文件:
- /* DO NOT EDIT THIS FILE - it is machine generated */
- #include <jni.h>
- /* Header for class com_github_jni_demo_TestJNI */
-
- #ifndef _Included_com_github_jni_demo_TestJNI
- #define _Included_com_github_jni_demo_TestJNI
- #ifdef __cplusplus
- extern "C" {
- #endif
- /*
- * Class: com_github_jni_demo_TestJNI
- * Method: HelloWord
- * Signature: (Ljava/lang/String;)Ljava/lang/String;
- */
- JNIEXPORT jstring JNICALL Java_com_github_jni_1demo_TestJNI_HelloWord
- (JNIEnv *, jobject, jstring);
-
- #ifdef __cplusplus
- }
- #endif
- #endif
复制代码
然后右键 app >New> Folder > JNI Folder 生成jni目录如图: 
然后拷贝com_github_jni_demo_TestJNI.h到jni目录下面: 
生成 .C 文件
右键jni,生成com_github_jni_demo_TestJNI.cpp文件: 
拷贝以下代码到 .cpp 文件中:
- #include <stdio.h>
- #include <stdlib.h>
- #include "com_github_jni_demo_TestJNI.h"
- JNIEXPORT jstring JNICALL Java_com_github_jni_1demo_TestJNI_HelloWord
- (JNIEnv *env, jobject, jstring str) {
- return str;
- }
复制代码
build.gradle 配置 ndk 在defaultConfig节点下加入如下代码:
- ndk {
- moduleName "TestJNI"
- abiFilters "armeabi", "armeabi-v7a", "x86"
- }
复制代码
点击 Build > Make Project 如图: 
编译成功后,打开 build > intermediates > ndk > debug > lib 下查看生成的 .so 文件: 
Java中调用JNI
记得把生成的 .so 文件拷贝到项目的 libs 目录下:
 接着在Java中调用JNI:
- package com.github.jni_demo;
-
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
-
- public class MainActivity extends AppCompatActivity {
- static { // 加载动态库
- System.loadLibrary("TestJNI");
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- TestJNI testJNI=new TestJNI();
- Log.e("---------------","************"+testJNI.HelloWord("恭喜你,调用成功!"));
- }
- }
复制代码

这样你就生成了一个属于自己的 .so 文件。 捡代码论坛(bbs.jiandaima.com)整理提供 .. |