'How to notify when an update is available without restarting the app in Xamarin C#
I have created methods that compare a locally downloaded json file with the json of the url. If the downloaded file is different from the json of the url. When you restart the app, it only gives the message on the main page that an update is available.
This looks like this in the main page
protected override async void OnAppearing()
{
base.OnAppearing();
{
await Api.UpdateContentJson();
}
}
This does the check if you are on the main page with a working internet connection when you restart the app.
But I want it to say it directly anywhere in the app without having to restart the app with a working internet connection!
This is my code to compare the JSON and download if different
public static async Task UpdateContentJson()
{
string FolderName = MainPage.GetJsonName();
try
{
const string jsonName = "getlatest.json";
string updateCheckJsonPath = path + "/" + jsonName;
string jsonFromUrl = await GetNewestMediaVersion();
string currentVersion = CurrentVersionContentJson();
if (!currentVersion.Equals(jsonFromUrl))
{
bool result = await Application.Current.MainPage.DisplayAlert("Update",
"New changes in the courses are available! Do you want to update it?", "Yes", "No");
//install newest update
if (result)
{
await DownloadJson();
}
}
else
{
return;
}
}
catch (Exception)
{
}
}
//for reading current versions json
private static string CurrentVersionJson()
{
RootAppVersion rootObject = new RootAppVersion();
string currentVersion;
using (StreamReader r = new StreamReader(path + "/" + "getappversion.json"))
{
currentVersion = r.ReadToEnd();
rootObject = JsonSerializer.Deserialize<RootAppVersion>(currentVersion);
}
return currentVersion;
}
//for getting the newest content version json from url
private static async Task<string> GetNewestMediaVersion()
{
WebClient client = new WebClient();
const string url = "https://test.getappversion.cloud/getappversion";
client.Headers.Add("Authorization", await Header.GetAuthorizationHeader());
string jsonFromUrl = client.DownloadString(url);
return jsonFromUrl;
}
How can I get this to check for the update all the time, and not just when I launch the app on the main page?
Solution 1:[1]
How can I get this to check for the update all the time, and not just when I launch the app on the main page?
You can take a look at Device class in Xamarin.Forms and particularly at StartTimer method.
Given that, you can setup your timer :
Device.StartTimer(TimeSpan.FromHours(1.0), CheckAndUpdate);
And add method CheckAndUpdate:
private bool CheckAndUpdate()
{
UpdateContentJson();
return true;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jessie Zhang -MSFT |
