如果我设置 minifyEnabled = true
在我的 Android 应用程序的 Gradle 设置中,调用 JNI 函数 RegisterNatives()
从 JNI 共享库不再找到它的目标类。我尝试了许多 ProGuard 规则,但仍然无法使其正常工作。
java 代码:
package net.pol_online.hyper;
...
public class Hyper extends Application {
...
public native static void initializeLibrary(Context context, int maxImageMemoryCacheSize);
...
}
JNI代码:
static JNINativeMethod _methods[] = {
{"initializeLibrary", "(Landroid/content/Context;I)V", reinterpret_cast<void*>(&_InitializeLibrary)},
...
}
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
...
_hyperClass = env->FindClass("net/pol_online/hyper/Hyper");
jint error = env->RegisterNatives(_hyperClass, _methods, sizeof(_methods) / sizeof(JNINativeMethod));
assert(error == JNI_OK);
...
}
Gradle build设置(使用 experimental Gradle NDK plug-in for Android Studio):
android.buildTypes {
release {
minifyEnabled = true
proguardFiles.add(file("proguard-rules.txt"))
ndk.with {
CFlags.add("-Werror")
cppFlags.add("-Werror")
}
}
}
ProGuard 规则:
-keep class butterknife.** {
*;
}
-keep class **$$ViewBinder {
*;
}
-keepclasseswithmembernames class * {
@butterknife.* <fields>;
}
-keepclasseswithmembernames class * {
@butterknife.* <methods>;
}
-dontwarn butterknife.internal.**
-keep public class net.pol_online.hyper.**
-dontnote android.support.v4.**
-dontwarn android.support.v4.**
启动时崩溃:
Failed to register native method net.pol_online.hyper.Hyper.initializeLibrary(Landroid/content/Context;I)V in /data/app/net.pol_online.hyper-1/base.apk
java.lang.NoSuchMethodError: no static or non-static method "Lnet/pol_online/hyper/Hyper;.initializeLibrary(Landroid/content/Context;I)V"'
最佳答案
您不包括 android 的默认 Proguard 配置:
proguardFiles getDefaultProguardFile('proguard-android.txt')
其中包括保留所有 native 方法的配置:
-keepclasseswithmembernames class * {
native <methods>;
}
这也应该可以解决这个问题,强烈建议这样做。
关于android-ndk - 运行 ProGuard 后 JNI RegisterNatives() 找不到类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37626799/