4

Android Studio JNI 开发简单案例

 2 years ago
source link: http://www.androidchina.net/5744.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

进程保活,热修复,硬件接入等等都需要底层的支持,而底层代码是 C 、C++ 写的,那么在 Android 中怎么调用底层的库呢?这里就需要了解 JNI 技术。

Android Studio 出来两年多了,网上针对 AS 开发 JNI 工程资源比较少,针对于此,我特意写下本篇博客,希望能对大家有所帮助。

jni

  • 项目关联NDK ,具体操作如图:

右键你的工程项目,选择 【Open Module Settings】

jni

在 【Android NDK location】配置 NDK 的按着目录:

jni

最后在 项目根目录 【gradle.properties】 下加上:

android.useDeprecatedNdk=true

jni

JNI实现

新建 JNI_DEMO 项目,完成以上的配置工作。我的项目路径为:D:\Android_Study_Demos\JNI_DEMO

生成 .h 文件

新建TestJNI

public class TestJNI {

   public native String HelloWord(String str);

}

jni

cmd命令下面,cdjava目录,输入javah -jni com.github.jni_demo.TestJNI命令,生成 .h 文件:

jni

注意: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 >NewFolder > JNI Folder 生成jni目录如图:

jni

然后拷贝com_github_jni_demo_TestJNI.hjni目录下面:

jni

生成 .C 文件

右键jni,生成com_github_jni_demo_TestJNI.cpp文件:

jni

拷贝以下代码到 .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 如图:

jni

编译成功后,打开 build > intermediates > ndk > debug > lib 下查看生成的 .so 文件:

jni

Java中调用JNI

记得把生成的 .so 文件拷贝到项目的 libs 目录下:

jni

接着在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("恭喜你,调用成功!"));
    }
}

jni

这样你就生成了一个属于自己的 .so 文件。

转载请注明:Android开发中文站 » Android Studio JNI 开发简单案例


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK