android-ndk - 运行 ProGuard 后 JNI RegisterNatives() 找不到类方法

标签 android-ndk proguard android-proguard

如果我设置 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.apkjava.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/

相关文章:

android - 如果我从我的 Android 应用程序中排除所有 64 位库,它是否会完全以 32 位模式运行?

android - 为安卓安装 Tesseract

Android proguard 后退箭头未显示(尽管在调试 APK 中工作)

java - Android Facebook SDK Eclipse Proguard

android - 共享对象、符号、C/C++ lib 链接和加载

android - C++ NDK 中的 C2DM

android - 如何在 android studio gradle 中降级 proguard 版本?

xamarin - 错误MSB6006 : "java.exe" exited with code 1 when ProGuard enabled

android - 如何在 Eclipse 和 Debug模式下使用混淆器?

java - 混淆模块/库