安卓开发解决java.lang.UnsatisfiedLinkError

产生原因:

在安卓开发中,引用了多方的sdk的so库之后,不同机型之间就会发生这样一个错误:

Java.lang.UnsatisfiedLinkError,这是由于程序运行的时候未获取到争取的so库包产生的一个错误:


你原先的项目中只使用了A公司提供的so包,他只提供了armeabi这个架构的so包,后来项目需要又引用了B公司的提供的sdk,里面提供的so包还挺全的,arm64-v8a,armeabi-v7a,mips,mips64,x86等等,结果你就全放进去了, 后来发现突然某手机就出现了崩溃,然后一般都是因为这个问题Java.lang.UnsatisfiedLinkError。


解决过程:

1.引入多种 so 库,如果只需要其中的几种,可以在gradle中添加下面的配置(比如):

productFlavors {
  arm {
    ndk {
      abiFilters "armeabi-v7a", "armeabi"
    }
  }
  x86 {
    ndk {
      abiFilter "x86"
    }
  }
}
这样在编译的时候arm只会引入armeabi-v7a和armeabi,在x86只会引入x86包

同时需要在 gradle.properties 中添加:


android.useDeprecatedNdk = true

2.后面我发现在小米4、锤子 T2 等手机上打开接入了这个库的 app 直接闪退了。经过分析发现,在小米 4、锤子 T2 等手机上运行我们的 app ,系统会先去找 arm64-v8a 这个目录下的 so 文件,如果不存在还好,偏偏我的 app 存在 arm64-v8a 目录,此时因为找不到目录下的 so 文件,就直接报 java.lang.UnsatisfiedLinkError:couldn't find "*****.so" 的错了。

在 stackoverflow 上找到了解决的答案:

When you install an APK on Android, the system will look for native libraries directories (armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips64, mips) inside the lib folder of the APK, in the order determined by Build.SUPPORTED_ABIS.

If your app happen to have an arm64-v8a directory with missing libs, the missing libs will not be installed from another directory, the libs aren't mixed. That means you have to provide the full set of your libraries for each architecture.

So, to solve your issue, you can remove your 64-bit libs from your build, or set abiFilters to package only 32-bit architectures:

android {
    defaultConfig {
        ndk {
            abiFilters "x86", "armeabi-v7a"
        }
    }
    buildTypes {
   
}

如果照上面的配置,那打包时就只会把 "x86", "armeabi-v7a" 这两个目录及其下的 so 文件打包进 apk 。我们的问题也解决了,因为系统也只能找这两个目录下的 so 文件了。


猜你喜欢

转载自blog.csdn.net/android_koukou/article/details/75007286