在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的官方文档以获取更多详细信息。