Android——JNI开发(studio)

一、studio下JNI开发
1.创建项目时 Include C++ support

2.即可以在建好的模板下开发
这里写图片描述

二、如何自定义cpp
1.新建test.cpp文件

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_example_jie_jnidemo_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from c++ test";
    return env->NewStringUTF(hello.c_str());
}

2.在External Build Files中添加lib

//这个是之前的studio创建的模板
add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/native-lib.cpp )

//这个是我们自定义的cpp
add_library( # Sets the name of the library.
             test

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/test.cpp)

3.读取lib

// Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("test");
    }

4.调用native方法并更新UI

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

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

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

5.大功告成
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42164949/article/details/81412476