Show a display popup for update when update available from playstore

HarshitaHarshita INMember ✭✭✭

I want to show a display popup for update apk(if update available from playstore)when user open the application.If user click on "OK" then it will open the playstore for update apk.
How to do this in xamarin forms?

Best Answers

  • HarshitaHarshita IN ✭✭✭
    Accepted Answer

    Here is the solution:

    Create a Interface on PCL =>

    public interface ILatest
        {
            //
            // Summary:
            //     Gets the version number of the current app's installed version.
            string InstalledVersionNumber { get; }
    
            //
            // Summary:
            //     Gets the version number of the current app's latest version available in the
            //     public store.
            //
            // Returns:
            //     The current app's latest version number.
            Task<string> GetLatestVersionNumber();
            //
            // Summary:
            //     Gets the version number of an app's latest version available in the public store.
            //
            // Parameters:
            //   appName:
            //     Name of the app to get.
            //
            // Returns:
            //     The specified app's latest version number
            Task<string> GetLatestVersionNumber(string appName);
            //
            // Summary:
            //     Checks if the current app is the latest version available in the public store.
            //
            // Returns:
            //     True if the current app is the latest version available, false otherwise.
            Task<bool> IsUsingLatestVersion();
            //
            // Summary:
            //     Opens the current app in the public store.
            Task OpenAppInStore();
            //
            // Summary:
            //     Opens an app in the public store.
            //
            // Parameters:
            //   appName:
            //     Name of the app to open.
            Task OpenAppInStore(string appName);
        }
    

    Implement the interface class to android project=>

    [assembly: Dependency(typeof(LatestVersionCheck))]
    namespace YourProjectNameS.Android
    {
        public class LatestVersionCheck : ILatest
        {
            string _packageName => global::Android.App.Application.Context.PackageName;
            string _versionName => global::Android.App.Application.Context.PackageManager.GetPackageInfo(global::Android.App.Application.Context.PackageName, 0).VersionName;
    
            /// <inheritdoc />
            public string InstalledVersionNumber
            {
                get => _versionName;
            }
    
            /// <inheritdoc />
            public async Task<bool> IsUsingLatestVersion()
            {
                bool isLatest = false;
                var latestVersion = string.Empty;
    
                try
                {
                    latestVersion = await GetLatestVersionNumber();
    
                    isLatest = Version.Parse(latestVersion).CompareTo(Version.Parse(_versionName)) <= 0;
                }
                catch (Exception e)
                {
                    // throw new LatestVersionException($"Error comparing current app version number with latest. Version name={_versionName} and lastest version={latestVersion} .", e);
                }
                return isLatest;
            }
    
            /// <inheritdoc />
            public async Task<string> GetLatestVersionNumber()
            {
                return await GetLatestVersionNumber(_packageName);
            }
    
            /// <inheritdoc />
            public async Task<string> GetLatestVersionNumber(string appName)
            {
                if (string.IsNullOrWhiteSpace(appName))
                {
                    throw new ArgumentNullException(nameof(appName));
                }
    
                var version = string.Empty;
                var url = $"https://play.google.com/store/apps/details?id={appName}&hl=en";
    
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    using (var handler = new HttpClientHandler())
                    {
                        using (var client = new HttpClient(handler))
                        {
                            using (var responseMsg = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                            {
                                if (!responseMsg.IsSuccessStatusCode)
                                {
                                    //throw new LatestVersionException($"Error connecting to the Play Store. Url={url}.");
                                }
    
                                try
                                {
                                    var content = responseMsg.Content == null ? null : await responseMsg.Content.ReadAsStringAsync();
    
                                    var versionMatch = Regex.Match(content, "<div[^>]*>Current Version</div><span[^>]*><div><span[^>]*>(.*?)<").Groups[1];
    
                                    if (versionMatch.Success)
                                    {
                                        version = versionMatch.Value.Trim();
                                    }
                                }
                                catch (Exception e)
                                {
                                    // throw new LatestVersionException($"Error parsing content from the Play Store. Url={url}.", e);
                                }
                            }
                        }
                    }
                }
    
                return version;
            }
    
            /// <inheritdoc />
            public Task OpenAppInStore()
            {
                return OpenAppInStore(_packageName);
            }
    
            /// <inheritdoc />
            public Task OpenAppInStore(string appName)
            {
                if (string.IsNullOrWhiteSpace(appName))
                {
                    throw new ArgumentNullException(nameof(appName));
                }
    
                try
                {
                    var intent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse($"market://details?id={appName}"));
                    intent.SetPackage("com.android.vending");
                    intent.SetFlags(ActivityFlags.NewTask);
                    global::Android.App.Application.Context.StartActivity(intent);
                }
                catch (ActivityNotFoundException)
                {
                    var intent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse($"https://play.google.com/store/apps/details?id={appName}"));
                    global::Android.App.Application.Context.StartActivity(intent);
                }
    
                return Task.FromResult(true);
            }
        }
    }
    

    Lets call the methods form PCL :) =>

    bool isLatestVersion = await DependencyService.Get<ILatest>().IsUsingLatestVersion();
                if (!isLatestVersion)
                {
                    bool res = await DisplayAlert("Message", "New version Available,do you want to update it?", "Update", "Cancel");
                    if (res)
                    {
                        await DependencyService.Get<ILatest>().OpenAppInStore();
                    }
                }
    
  • HarshitaHarshita IN ✭✭✭
    Accepted Answer

    @JohnHardman
    I tested this code on 5.0 and upper versions only.May be it works fine on each devices :(

Answers

  • amirvenusamirvenus USMember ✭✭✭

    A good question

    Don't take this as an answer, but I guess one way of doing it (and probably the worst way as well) is to compare the current application's version with the one stored on the server and check versions using a simple HttpClient call to the server.

    Or to check the current version vs the version advertised on the Google Play page of the App.

    Perhaps some HtmlAgilityPack-ing would be required.

    I look forward to hearing others' answers as well. I am sure there must be an easier way to do it.

  • HarshitaHarshita INMember ✭✭✭
    edited August 2018

    @amirvenus
    How to get the apk version from playstore using HttpClient?

  • HarshitaHarshita INMember ✭✭✭
    Accepted Answer

    Here is the solution:

    Create a Interface on PCL =>

    public interface ILatest
        {
            //
            // Summary:
            //     Gets the version number of the current app's installed version.
            string InstalledVersionNumber { get; }
    
            //
            // Summary:
            //     Gets the version number of the current app's latest version available in the
            //     public store.
            //
            // Returns:
            //     The current app's latest version number.
            Task<string> GetLatestVersionNumber();
            //
            // Summary:
            //     Gets the version number of an app's latest version available in the public store.
            //
            // Parameters:
            //   appName:
            //     Name of the app to get.
            //
            // Returns:
            //     The specified app's latest version number
            Task<string> GetLatestVersionNumber(string appName);
            //
            // Summary:
            //     Checks if the current app is the latest version available in the public store.
            //
            // Returns:
            //     True if the current app is the latest version available, false otherwise.
            Task<bool> IsUsingLatestVersion();
            //
            // Summary:
            //     Opens the current app in the public store.
            Task OpenAppInStore();
            //
            // Summary:
            //     Opens an app in the public store.
            //
            // Parameters:
            //   appName:
            //     Name of the app to open.
            Task OpenAppInStore(string appName);
        }
    

    Implement the interface class to android project=>

    [assembly: Dependency(typeof(LatestVersionCheck))]
    namespace YourProjectNameS.Android
    {
        public class LatestVersionCheck : ILatest
        {
            string _packageName => global::Android.App.Application.Context.PackageName;
            string _versionName => global::Android.App.Application.Context.PackageManager.GetPackageInfo(global::Android.App.Application.Context.PackageName, 0).VersionName;
    
            /// <inheritdoc />
            public string InstalledVersionNumber
            {
                get => _versionName;
            }
    
            /// <inheritdoc />
            public async Task<bool> IsUsingLatestVersion()
            {
                bool isLatest = false;
                var latestVersion = string.Empty;
    
                try
                {
                    latestVersion = await GetLatestVersionNumber();
    
                    isLatest = Version.Parse(latestVersion).CompareTo(Version.Parse(_versionName)) <= 0;
                }
                catch (Exception e)
                {
                    // throw new LatestVersionException($"Error comparing current app version number with latest. Version name={_versionName} and lastest version={latestVersion} .", e);
                }
                return isLatest;
            }
    
            /// <inheritdoc />
            public async Task<string> GetLatestVersionNumber()
            {
                return await GetLatestVersionNumber(_packageName);
            }
    
            /// <inheritdoc />
            public async Task<string> GetLatestVersionNumber(string appName)
            {
                if (string.IsNullOrWhiteSpace(appName))
                {
                    throw new ArgumentNullException(nameof(appName));
                }
    
                var version = string.Empty;
                var url = $"https://play.google.com/store/apps/details?id={appName}&hl=en";
    
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    using (var handler = new HttpClientHandler())
                    {
                        using (var client = new HttpClient(handler))
                        {
                            using (var responseMsg = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                            {
                                if (!responseMsg.IsSuccessStatusCode)
                                {
                                    //throw new LatestVersionException($"Error connecting to the Play Store. Url={url}.");
                                }
    
                                try
                                {
                                    var content = responseMsg.Content == null ? null : await responseMsg.Content.ReadAsStringAsync();
    
                                    var versionMatch = Regex.Match(content, "<div[^>]*>Current Version</div><span[^>]*><div><span[^>]*>(.*?)<").Groups[1];
    
                                    if (versionMatch.Success)
                                    {
                                        version = versionMatch.Value.Trim();
                                    }
                                }
                                catch (Exception e)
                                {
                                    // throw new LatestVersionException($"Error parsing content from the Play Store. Url={url}.", e);
                                }
                            }
                        }
                    }
                }
    
                return version;
            }
    
            /// <inheritdoc />
            public Task OpenAppInStore()
            {
                return OpenAppInStore(_packageName);
            }
    
            /// <inheritdoc />
            public Task OpenAppInStore(string appName)
            {
                if (string.IsNullOrWhiteSpace(appName))
                {
                    throw new ArgumentNullException(nameof(appName));
                }
    
                try
                {
                    var intent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse($"market://details?id={appName}"));
                    intent.SetPackage("com.android.vending");
                    intent.SetFlags(ActivityFlags.NewTask);
                    global::Android.App.Application.Context.StartActivity(intent);
                }
                catch (ActivityNotFoundException)
                {
                    var intent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse($"https://play.google.com/store/apps/details?id={appName}"));
                    global::Android.App.Application.Context.StartActivity(intent);
                }
    
                return Task.FromResult(true);
            }
        }
    }
    

    Lets call the methods form PCL :) =>

    bool isLatestVersion = await DependencyService.Get<ILatest>().IsUsingLatestVersion();
                if (!isLatestVersion)
                {
                    bool res = await DisplayAlert("Message", "New version Available,do you want to update it?", "Update", "Cancel");
                    if (res)
                    {
                        await DependencyService.Get<ILatest>().OpenAppInStore();
                    }
                }
    
  • JohnHardmanJohnHardman GBUniversity mod
    edited September 2018

    @Harshita - I haven't gone through the code in detail yet, but was wondering if you have found there is a minimum Android version that the code above works on? The reason for asking is that a plugin that does the same thing (see https://github.com/edsnider/latestversionplugin ) is documented as needing Android 10.0+ (does that even exist yet?). I want to support Android versions as early as 4.x if possible. Do you know if the code that you posted will work on 4.x?

  • HarshitaHarshita INMember ✭✭✭
    Accepted Answer

    @JohnHardman
    I tested this code on 5.0 and upper versions only.May be it works fine on each devices :(

Sign In or Register to comment.