JNI Hello Word

1.先new  Android studio  project   

2.建一个类叫JNIHello

package com.sina.smallletters.myapplication;

/**
 * @author SmallLetters
 */
public class JNIHello {
    
    public static native String sayHello();


    static {
        System.loadLibrary("hello");   //库的名字
    }
    
}

3:选择JNIHello右键打开terminal 到 这个位置输入 javac  JNIHello.java生成class文件 

JNI Hello Word_第1张图片

D:\Android--workspace\jikexueyuan\Material & code\NDK\MyApplication\app\src\main\java\com\sina\smallletters\myapplication>javac JNIHello.java

4:使用javah生成.h文件 cd.. 到java的下层目录 输入 javah -jni com.sina.smallletters.myapplication.JNIHello

D:\Android--workspace\jikexueyuan\Material & code\NDK\MyApplication\app\src\main\java>javah -jni com.sina.smallletters.myapplication.JNIHello

5.然后选择JNIHello   new ->folder->jni folder 然后勾选上 选择finish 建立 jni 文件

JNI Hello Word_第2张图片

6.把生成的 .h 文件剪切到 jni 文件下。

7.jni 文件夹下  new  C/C++ Source File       名字写 hello    其他默认  确定

8.把 .h  文件的  方法 复制到 刚刚 新建的 hello.cpp 文件夹里   记得 前面加上 include  " .h里面的class 加上 .h "

#include "com_sina_smallletters_myapplication_JNIHello.h"

JNIEXPORT jstring JNICALL Java_com_sina_smallletters_myapplication_JNIHello_sayHello
        (JNIEnv *env, jclass obj){

    return  (*env).NewStringUTF("hello word");
}

9.在CMakeLists.txt  文件夹配置库

add_library( # Sets the name of the library.
        hello                       //设置库的 名字 

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        src/main/jni/hello.cpp)     //hello.cpp 的路径

10.然后就是 运行了

package com.sina.smallletters.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

/**
 * @author SmallLetters
 */
public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv =  findViewById(R.id.sample_text);
        tv.setText(JNIHello.sayHello());
    }
}

源代码 GitHub:https://github.com/smallletters/sample-code

如果其中报错的话看看 local.properties 和 gradle.properties 
local.properties 文件

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Wed Nov 14 20:27:37 CST 2018
ndk.dir=D\:\\Android\\android-sdk_r24.4.1-windows\\android-sdk-windows\\ndk-bundle
sdk.dir=D\:\\Android\\android-sdk_r24.4.1-windows\\android-sdk-windows

 

你可能感兴趣的:(Android,studio)