简体   繁体   English

如果多个活动和服务需要,在 Android 中加载本机库的位置

[英]Where to load a native library in Android if required by multiple activies and services

Some of my Kotlin classes are implemented by a native library (Rust using jni).我的一些 Kotlin 类是由本机库(使用 jni 的 Rust)实现的。 These classes are used in most of the activies and by one sync service (a second service may come later).这些类用于大多数活动和一个同步服务(第二个服务可能会稍后出现)。

What is the recommended solution to load this library and handle loading errors (for example sending a bug report if loading fails)?加载此库并处理加载错误的推荐解决方案是什么(例如,如果加载失败,则发送错误报告)?

Basic examples loads a library in the MainActivity.onCreate .基本示例在MainActivity.onCreate加载一个库。 Or often I see a static block inside the MainActivity class.或者我经常在 MainActivity 类中看到一个静态块。 Another method may be loading the library in a derived class from Application .另一种方法可能是从Application的派生类中加载库。 But I'm not sure if there is only one Application instance for all activities and services or if one `` Application``` instance is created for each service and another one for all activities.但我不确定是否只有一个Application实例用于所有活动和服务,或者是否为每个服务创建了一个“Application”实例而为所有活动创建了另一个实例。

So my question is: where to put System.loadLibrary() ?所以我的问题是:把System.loadLibrary()放在哪里?

Yes, the Application is a singleton for the whole Android app.是的,该应用程序是整个 Android 应用程序的单例。 But you should not worry, LoadLibrary() does nothing if the library had been loaded before.但是您不必担心,如果之前已加载该库,LoadLibrary() 不会执行任何操作。 So, the best practice is to add LoadLibrary in static blocks of all classes that depend on this library.因此,最佳实践是在依赖此库的所有类的静态块中添加 LoadLibrary。

Consider using ReLinker library that provides logging and also workarounds for some widespread problems with loading native libraries.考虑使用ReLinker库,该库提供日志记录以及解决加载本机库时出现的一些普遍问题的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM