以编程方式获取我的 Android 应用程序中库的版本 [英] Get the version of a library in my Android app programmatically
问题描述
我的 Android 应用程序中有一个库,例如 UnityAds.我想在运行时获取版本名称和版本代码.我写了下面的代码,但总是发生异常.以编程方式获取此信息的最佳做法是什么?
I have a library in my Android app like UnityAds. I want to get the version name and the version code of it in runtime. I wrote the below code, but always exception occurred. What is the best practice to get this information programmatically?
实现'com.unity3d.ads:unity-ads:3.7.1'
implementation 'com.unity3d.ads:unity-ads:3.7.1'
try {
Log.d("Version", getPackageManager().getPackageInfo("com.unity3d.ads", 0).versionName);
} catch (PackageManager.NameNotFoundException e) {
Log.e("error", e.getMessage());
}
推荐答案
这行不通,PackageManager API 可帮助您使用包名称查找来检查是否安装了任何有效的包/应用.
That won’t work, PackageManager APIs help you check for any valid packages/apps installed using a package name lookup.
由于库位于您自己的包的类路径中,因此在运行时引用这些 id 的唯一方法是使用工作流在编译期间记录这些 ID,并在运行时将其公开给您的应用程序.
Since the library is in the class path for your own package the only way to reference these ids at runtime would be to have a workflow to record these during compilation and expose it to your application at runtime.
以下方法可行:
自定义 gradle 插件将类路径中的所有库捕获到可以在运行时读取的资产中,类似于 https://github.com/google/play-services-plugins
Custom gradle plugin to capture all libraries in classpath into assets which can be read at runtime, something similar to https://github.com/google/play-services-plugins
使用 (1) 您无法方便地将其扩展到多个库,因此它仅适用于非常特定的需求.
With (1) you can’t scale it for multiple libraries conveniently so it’s only useful for very specific needs.
(2) 可能需要对您的用例进行一些自定义(添加版本信息),但绝对是可扩展的.
(2) might require some customisations for your usecase (adding version info) but is definitely scalable.
这篇关于以编程方式获取我的 Android 应用程序中库的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!