問題描述
如何從共享庫中獲取版本信息到 Android 清單中? (How to get version info from a shared library into the Android manifest?)
我們有一個包含版本信息的共享庫,我們的 Visual Studio 解決方案中的所有項目都引用它。
在大多數情況下,我們可以引用每個項目的版本字符串,並且 dll 反映相應的信息。
我的問題是,我們的 Android 應用程序(基於 xamarin)。它有一個包含 versionName 和 versionCode 的清單文件。
我們如何讓我們的 android 清單文件中的這些值從我們的共享項目中讀取?
參考解法
方法 1:
Note: I do not know anything about xamarin.
In java you can get the versioninfo from the manifest like this
public static String getAppVersionName(final Context context) {
try {
final String versionName = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0).versionName;
return versionName;
} catch (final NameNotFoundException e) {
}
return null;
}
I assume that xamarin has some mechanism to call PackageManager to get Packageinfo, too
方法 2:
My understanding is that, it is not possible. Because
The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code.
From Google's documentation
So this is a file that is required before the App builds.
C# Code in Shared Project (SAP/PCL) is ready to be used only after successful Compilation. So logically setting the Version Code and Version Name in Android Manifest File from Shared logic is not possible.
Another standard approach would be to set it from String Resource (XML) file in Android. You may have to copy and paste the value from Shared Project to strings.xml file and refer it in manifest, like
@string/versionCode
方法 3:
You could do this by using a Dependency Service. Here's a great article on them: https://developer.xamarin.com/guides/xamarin‑forms/dependency‑service/
The idea would be your Dependency Service would expose the Android specific information to the shared code library.
For instance you might have an interface in your common code declared such as:
public interface IPlatformVersionInfo
{
string GetOSVersion ();
}
Now, in your Android library you would implement it:
public class PlatformVersionInfo : IPlatformVersionInfo
{
public string GetOSVersion () {
return Android.OS.Build.VERSION.SdkInt.ToString ();
}
}
Finally, in your common code you would use your dependency service of choice to invoke an instance of it:
var osVersion = DependencyService.Get<IPlatformVersionInfo>().GetOSVersion ();
Of course this is somewhat pseudo‑code and depending what dependency service you choose the code may look a bit different.