Native C++
Name
Package name
Save location
Language
Minimum SDK
C++ Standard
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 { ...... }
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} )
#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()); }
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++ 代碼已經生效了。android
至此,咱們已經學會了在 Android 項目中使用 C++ 代碼。git
代碼:github
NDKJNIday01app
參考資料:ide