我想要来自 ndk 库的 different string value。 因为我有两种 flavor 的演示和现场直播,所以我想要值“你好,我来自演示”,用于演示 flavor ,而对于现场 flavor ,我想要“你好,我来自现场”
这是我的java文件代码
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) 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();
这是我的cpp文件代码
#include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring JNICALL
Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "hello I am from demo";
return env->NewStringUTF(hello.c_str());
}
这是我的build.gradle文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.de.demo.ndk2"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
flavorDimensions "default"
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
demo
{
// applicationId "com.readwhere.whitelabel.test"
//applicationId "com.android.rwstaging"
applicationId "com.android.demo"
versionName "2.1"
dimension "default"
externalNativeBuild {
cmake {
targets "native-lib-demo","my-executible- demo"
}}
}
live
{
// applicationId "com.readwhere.whitelabel.test"
//applicationId "com.android.rwstaging"
applicationId "com.android.live"
versionName "2.1"
dimension "default"
}}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
我在演示文件夹和主文件夹中粘贴了相同的 cpp 文件 但可以完成我的任务。任何帮助将不胜感激 这是一些引用链接
https://developer.android.com/studio/projects/gradle-external-native-builds.html
How to set CmakeLists path in product flavor for each Android ABI?
最佳答案
可能,在编译时实现您的目标的最少代码是根据口味设置 cppFLags:
productFlavors {
demo {
applicationId "com.android.demo"
versionName "2.1"
dimension "default"
externalNativeBuild.cmake {
cppFlags '-DDEMO'
}
}
live {
applicationId "com.android.live"
versionName "2.1"
dimension "default"
externalNativeBuild.cmake {
cppFlags '-DLIVE'
}
}
}
在你的cpp文件中
#ifdef DEMO
std::string hello = "hello I am from demo";
#endif
#ifdef LIVE
std::string hello = "hello I am from live";
#endif
或者您可以使用 stingify这样的模式 answer .
当然,您的条件编译不限于字符串变化。
关于java - NDK 支持不同的 Product Flavor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47350245/