Get current app's build version - Xamarin.Android

Tushar patel picture Tushar patel · Sep 23, 2016 · Viewed 13.8k times · Source

I need to display the app's build version in my settings page.

So how can i get the versionCode and versionName from AndroidManifest.xml file programmatically.

Or

Is there any way to get the build version programmatically in xamarin.forms.

Answer

Mario Galván picture Mario Galván · Sep 23, 2016

With a Dependency service:

For iOS:

using Foundation;

[assembly: Xamarin.Forms.Dependency(typeof(Screen_iOS))]

namespace XXX.iOS
{
    public class Screen_iOS : IScreen
    {

        public string Version
        {
            get
            {
                NSObject ver = NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"];
                return ver.ToString();
            }
        }

    }
}

For Android:

using Xamarin.Forms;

[assembly: Dependency(typeof(ScreenAndroid))]

namespace XXX.Droid
{
    class ScreenAndroid : Java.Lang.Object, IScreen
    {

        public string Version
        {
            get
            {
                var context = Forms.Context;
                return context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
            }
        }

    }
}

And the interface:

interface IScreen
{
    string Version { get; }
}