在Android上部署C++應用需要使用Android NDK(Native Development Kit)和JNI(Java Native Interface)。以下是部署C++應用的基本步驟:
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
buildTypes {
...
release {
...
jniDebuggable true
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
cmake_minimum_required(VERSION 3.4.1)
add_library(native-lib SHARED src/main/cpp/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_example_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
public class MainActivity extends AppCompatActivity {
// Load the native library
static {
System.loadLibrary("native-lib");
}
// Declare the native method
private native String stringFromJNI();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call the native method and print the result
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
}
請注意,這只是一個簡單的示例,實際應用程序可能需要更多的配置和優化。建議參考Android NDK和JNI的官方文檔以獲取更多詳細信息。