TOC](Android Studio 3.4 NDK编程)
打开File->Setting,安装以下工具:
路径:app/src/main/java/com.android.MyTest/MainActivity.java
JAVA层声明NDK的包名和方法
package com.android.mytest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); //== NDK包名 == } @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(stringFromJNI()); } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ public native String stringFromJNI(); //== NDK方法 == }路径:app/src/main/cpp/native-lib.cpp
C++实现NDK方法
#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_android_mytest_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); }设置NDK生成的so包路径:app/src/main/jniLibs/
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}) # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. #cmake版本 cmake_minimum_required(VERSION 3.4.1) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. #设置NDK生成的so包路径:app/src/main/jniLibs/ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}) add_library( # Sets the name of the library. # 设置生成的NDK包名 native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). # 要编译的源文件,可以多个,使用空格间隔 native-lib.cpp) # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. target_link_libraries( # Specifies the target library. # 设置链接的NDK包名 native-lib # Links the target library to the log library # included in the NDK. ${log-lib})