创建项目
1. 选择一个项目模板
Native C++
2. 配置我们的项目
Name
Package name
Save location
Language
Minimum SDK
3. Customize C++ Support
C++ Standard
4. 查看第一个 NDK-JNI 项目
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.ihubin.ndkjni"
......
}
buildTypes {
......
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
}
dependencies {
......
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1)
add_library(
native-lib
SHARED
native-lib.cpp )
find_library(
log-lib
log )
target_link_libraries(
native-lib
${log-lib} )
native-lib.cpp
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_ihubin_ndkjni_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
MainActivity.java
package com.ihubin.ndkjni;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
public native String stringFromJNI();
}
运行项目
修改 C++ 代码,重新运行
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_ihubin_ndkjni_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
// std::string hello = "Hello from C++";
std::string hello = "NDK-JNI-day01";
return env->NewStringUTF(hello.c_str());
}
可以看到,我们修改的 C++ 代码已经生效了。
查看 APK
至此,我们已经学会了在 Android 项目中使用 C++ 代码。
代码:
参考资料: