JNI RegisterNatives() 在运行 ProGuard 后找不到类方法



如果我在 Android 应用的 Gradle 设置中设置minifyEnabled = true,则从 JNI 共享库中调用 JNI 函数RegisterNatives()不会再找到其目标类。我尝试了许多ProGuard规则,但仍然无法使其正常工作。

爪哇代码:

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

构建设置(使用 Android Studio 的实验性 Gradle NDK 插件):

android.buildTypes {
    release {
        minifyEnabled = true
        proguardFiles.add(file("proguard-rules.txt"))
        ndk.with {
            CFlags.add("-Werror")
            cppFlags.add("-Werror")
        }
    }
}

专业卫士规则:

-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')

其中包括保留所有本机方法的配置:

-keepclasseswithmembernames class * {
    native <methods>;
}

这也应该可以解决问题,强烈建议这样做。

最新更新