using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.Remoting.Contexts;
using System.Text;
using Shared.Common;
using Shared.Phone.Device.CommonForm;
namespace Shared.Phone.UserCenter.Abount
{
///
/// 关于的画面
///
public class AbountForm : EditorCommonForm
{
#region ◆ 变量____________________________
///
/// 是否正在更新中
///
public bool isUpdating;
///
/// The web client.
///
public WebClient webClient=new WebClient { };
///
/// 更新中
///
public Button updatingBtn;
///
/// distributedMark
///
public string distributedMark;
///
/// updateRow
///
public DeviceInfoRow updateRow;
///
/// 下载安卓apk的byte长度
///
public long ApkBytesTotalLength = 0;
#endregion
///
/// Initializes a new instance of the class.
///
public AbountForm()
{
}
///
/// 画面显示(底层会固定调用此方法,借以完成画面创建)
///
public void ShowForm()
{
//设置标题信息
base.SetTitleText(Language.StringByID(R.MyInternationalizationString.uAboutMe));
//初始化中部控件
this.InitMiddleFrame();
}
///
/// Closes the form.
///
public override void CloseFormBefore()
{
#if Android
//if (isUpdating == true)
//{
//var alert = new Alert(Language.StringByID(R.MyInternationalizationString.TIP), Language.StringByID(R.MyInternationalizationString.CancelUpdating), Language.StringByID(R.MyInternationalizationString.Cancel), Language.StringByID(R.MyInternationalizationString.Confrim));
//alert.Show();
//alert.ResultEventHandler += (send, e) =>
//{
// if (e)
// {
SetDownLoadBtnNoVisible();
CancelDownLoadApkAsync();
base.CloseFormBefore();
//}
// else
// {
// return;
// }
// };
//}
//else
//{
// base.CloseFormBefore();
//}
#elif iOS
base.CloseFormBefore();
#endif
}
///
/// 初始化中部控件
///
private void InitMiddleFrame()
{
bodyFrameLayout.BackgroundColor = ZigbeeColor.Current.GXCGrayBackgroundColor;
var logoFrameLayout = new FrameLayout
{
Height = Application.GetRealHeight(484),
BackgroundColor = ZigbeeColor.Current.GXCBackgroundColor
};
bodyFrameLayout.AddChidren(logoFrameLayout);
var logoBackground = new FrameLayout
{
Y = Application.GetRealHeight(104),
Width = Application.GetMinRealAverage(167),
Height = Application.GetMinRealAverage(167),
Gravity = Gravity.CenterHorizontal,
BackgroundColor = ZigbeeColor.Current.GXCButtonBlackSelectedColor,
Radius = (uint)Application.GetRealHeight(37),
};
logoFrameLayout.AddChidren(logoBackground);
var logoBtn = new Button()
{
Width = Application.GetMinRealAverage(144),
Height = Application.GetMinRealAverage(144),
UnSelectedImagePath = "Account/Logo_White.png",
Gravity = Gravity.Center
};
logoBackground.AddChidren(logoBtn);
var nameBtn = new Button()
{
Y = Application.GetRealHeight(294),
Width = Application.GetRealWidth(700),
Height = Application.GetRealHeight(60),
Gravity = Gravity.CenterHorizontal,
Text = "HDL Home",
TextSize = 15,
TextColor = ZigbeeColor.Current.GXCTextDeepBlackColor
};
logoFrameLayout.AddChidren(nameBtn);
var versionBtn = new Button()
{
Y = Application.GetRealHeight(366),
Width = Application.GetRealWidth(700),
Height = Application.GetRealHeight(50),
Gravity = Gravity.CenterHorizontal,
Text = $"{Language.StringByID(R.MyInternationalizationString.VersionCode)} {CommonPage.CodeIDString}",
TextSize = 12,
TextColor = ZigbeeColor.Current.GXCTextGrayColor
};
logoFrameLayout.AddChidren(versionBtn);
var versionFL = new FrameLayout
{
Y = Application.GetRealHeight(510),
//Height = Application.GetRealHeight(300),
Height = Application.GetRealHeight(300-127-12),
BackgroundColor = ZigbeeColor.Current.GXCBackgroundColor
};
bodyFrameLayout.AddChidren(versionFL);
//var SLARow = new DeviceInfoRow(12);
//SLARow.Init();
//SLARow.SetTipTitle(R.MyInternationalizationString.SLA);
//SLARow.NameText.TextAlignment = TextAlignment.CenterRight;
//versionFL.AddChidren(SLARow);
//SLARow.ClickBtn.MouseUpEventHandler += (sender, e) =>
//{
// var slaForm = new SLAForm();
// slaForm.AddForm();
//};
//updateRow = new DeviceInfoRow(12 + 127 + 12);
updateRow = new DeviceInfoRow(12);
updateRow.Init();
updateRow.SetTipTitle(R.MyInternationalizationString.UpdateVersion);
updateRow.NameText.TextAlignment = TextAlignment.CenterRight;
updateRow.HideLine(true);
updateRow.SetTitle(R.MyInternationalizationString.TheAppVersionIsNewest);
updateRow.CanClick(false);
updateRow.SetTitleColor(ZigbeeColor.Current.GXCTextGrayColor);
versionFL.AddChidren(updateRow);
updateRow.ClickBtn.MouseUpEventHandler += (sender, e) =>
{
UpdateVersion();
};
updatingBtn = new Button()
{
Y = Application.GetRealHeight(994),
Width = Application.GetRealWidth(556),
Height = Application.GetRealHeight(106),
Radius=(uint)Application.GetRealHeight(53),
BackgroundColor=ZigbeeColor.Current.GXCDailogBackGroundColor,
TextID = R.MyInternationalizationString.Updating,
TextSize=15,
TextColor = ZigbeeColor.Current.GXCTextWhiteColor,
Gravity=Gravity.CenterHorizontal
};
bodyFrameLayout.AddChidren(updatingBtn);
SetDownLoadBtnNoVisible();
CheckVersion();
}
///
/// CheckVersion
///
private void CheckVersion()
{
new System.Threading.Thread(async () =>
{
var re = await CanUpdateAsync();
if (re)
{
Application.RunOnMainThread(() =>
{
updateRow.CanClick(true);
updateRow.SetTitleColor(ZigbeeColor.Current.GXCButtonSelectedColor);
updateRow.SetTitle(R.MyInternationalizationString.Update);
});
}
})
{ IsBackground = true }.Start();
}
///
/// 设置进度控件不可见
///
private void SetDownLoadBtnNoVisible()
{
isUpdating = false;
updatingBtn.Visible = false;
}
///
/// 设置进度控件可见
///
private void SetDownLoadBtnVisible()
{
isUpdating = true;
updatingBtn.Visible = true;
updateRow.CanClick(false);
}
///
/// 检查版本
///
///
private async System.Threading.Tasks.Task CanUpdateAsync()
{
#if iOS
try
{
var versionResult = await RequestHttpsiOSAppVersionAsync();
if (versionResult == null || versionResult.Results == null)
{
return false;
}
var results = Newtonsoft.Json.Linq.JArray.Parse(versionResult.Results.ToString());
if (results[0] == null)
{
return false;
}
var newVersion = results[0]["version"]?.ToString();
var updateContent = results[0]["releaseNotes"]?.ToString();
if (newVersion != CommonPage.CodeIDString)
{
return true;
}
return false;
}
catch
{
return false;
}
#elif Android
try
{
var versionResult = await RequestHttpsAndroidAppVersionAsync();
if (versionResult == null)
{
return false;
}
if (int.Parse(versionResult.FirmwareVersion.Replace(".", "")) > int.Parse(CommonPage.CodeIDString.Replace(".", "")))
{
distributedMark = versionResult.DistributedMark;
return true;
}
return false;
}
catch (Exception ex)
{
return false;
}
#endif
}
///
/// 更新
///
private async void UpdateVersion()
{
#if iOS
OpenUrl();
#elif Android
try
{
var requestObj = new SendDataToServer.DownLoadAndroidApk
{
RequestVersion = CommonPage.RequestVersion,
DistributedMark = distributedMark
};
var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(requestObj);
var bytesTotalLengthResult = await CommonPage.Instance.RequestHttpsZigbeeAsync("FirmwareMana/DownloadPlatformUploadFirmwarePreLength", Encoding.UTF8.GetBytes(requestJson));
if (bytesTotalLengthResult == null || bytesTotalLengthResult.ResponseData == null)
{
CommonPage.Instance.ShowErrorInfoAlert(R.MyInternationalizationString.UpdateAppFail);
return;
}
var bytesTotalLength = Newtonsoft.Json.JsonConvert.DeserializeObject(bytesTotalLengthResult.ResponseData.ToString());
if (bytesTotalLength == 0)
{
CommonPage.Instance.ShowErrorInfoAlert(R.MyInternationalizationString.UpdateAppFail);
return;
}
ApkBytesTotalLength = bytesTotalLength;
var bytes = await DownLoadApkAsync("FirmwareMana/DownloadPlatformUploadFirmware", Encoding.UTF8.GetBytes(requestJson));
if (bytes == null)
{
CommonPage.Instance.ShowErrorInfoAlert(R.MyInternationalizationString.UpdateAppFail);
return;
}
if (bytes.ToString().Contains("DownloadFail"))
{
CommonPage.Instance.ShowErrorInfoAlert(R.MyInternationalizationString.FailedPleaseTryAgain);
return;
}
var path = System.IO.Path.Combine(Shared.IO.FileUtils.RootPath, "home.apk");
Shared.IO.FileUtils.WriteFileByBytes(path, bytes);
Install(Shared.Application.Activity);
}
catch (Exception ex)
{
System.Console.WriteLine($"下载失败--{ex.Message}");
}
#endif
}
#if iOS
///
/// 获取iOS-APP版本信息
///
/// The https app version async.
public async System.Threading.Tasks.Task RequestHttpsiOSAppVersionAsync()
{
try
{
var webClient = new WebClient { };
var result = await webClient.DownloadDataTaskAsync("https://itunes.apple.com/lookup?id=1461693569");
if (result == null)
{
return null;
}
return Newtonsoft.Json.JsonConvert.DeserializeObject(Encoding.UTF8.GetString(result));
}
catch
{
return null;
}
}
///
/// 跳转到APP Store
///
public void OpenUrl()
{
Uri url = new Uri("https://itunes.apple.com/cn/app/hdl-home/id1461693569?mt=8");
UIKit.UIApplication.SharedApplication.OpenUrl(url);
}
#elif Android
///
/// Install the specified context.
///
/// Context.
private static void Install(Android.Content.Context context)
{
//var file = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads), "home.apk");
var file = new Java.IO.File(System.IO.Path.Combine(Shared.IO.FileUtils.RootPath, "home.apk"));
var intent = new Android.Content.Intent(Android.Content.Intent.ActionInstallPackage);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.SetFlags(Android.Content.ActivityFlags.NewTask);
if (Android.OS.BuildVersionCodes.M < Android.OS.Build.VERSION.SdkInt)
{
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
var apkUri = Android.Support.V4.Content.FileProvider.GetUriForFile(context, "com.hdl.home.fileProvider", file);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.AddFlags(Android.Content.ActivityFlags.GrantReadUriPermission);
intent.SetDataAndType(apkUri, "application/vnd.android.package-archive");
}
else
{
intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/vnd.android.package-archive");
}
context.StartActivity(intent);
}
///
/// 获取 Android-APP 版本信息
///
/// The https app version async.
private async System.Threading.Tasks.Task RequestHttpsAndroidAppVersionAsync()
{
try
{
var requestOBJ = new SendDataToServer.GetAndroidApkInfoOBJ
{
Name = "ZigbeeApp",
RequestVersion = CommonPage.CodeIDString
};
var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(requestOBJ);
var result = await CommonPage.Instance.RequestHttpsZigbeeAsync("FirmwareMana/DetectionPlatformUploadFirmware", System.Text.Encoding.UTF8.GetBytes(requestJson));
if (result == null)
{
return null;
}
if (result.StateCode.ToUpper() == "SUCCESS")
{
if (result.ResponseData == null)
{
return null;
}
var responeData = Newtonsoft.Json.JsonConvert.DeserializeObject(result.ResponseData.ToString());
if (responeData == null || responeData.pageData == null || responeData.pageData.Count == 0)
{
return null;
}
int MaxIndex = 0;
int NewVersion = 0;
for (int i = 0; i < responeData.pageData.Count; i++)
{
var apkInfo = responeData.pageData[i];
var version = int.Parse(apkInfo.FirmwareVersion.Replace(".", ""));
if (version > NewVersion)
{
NewVersion = version;
MaxIndex = i;
}
}
return responeData.pageData[MaxIndex];
}
return null;
}
catch (Exception ex)
{
return null;
}
}
///
/// 下载安装apk
///
/// The load apk async.
/// 请求链接
/// 请求参数
private System.Threading.Tasks.Task DownLoadApkAsync(string requestUrl, byte[] byteData)
{
try
{
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
webClient.Headers.Add(HttpRequestHeader.Authorization, Config.Instance.Token);
webClient.UploadProgressChanged += Client_DownloadProgressChanged;
webClient.UploadDataCompleted += Client_UploadCompleted;
var result = webClient.UploadDataTaskAsync($"{CommonPage.RequestHttpsHost}/{requestUrl}", "POST", byteData);
if (result == null)
{
return null;
}
return result;
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
///
/// apk下载进度
///
/// Sender.
/// E.
void Client_DownloadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
//System.Console.WriteLine($"当前进度--{(int)(e.BytesReceived / (float)ApkBytesTotalLength * 100)} % --BytesReceived--{e.BytesReceived}--totalByte{e.TotalBytesToReceive}");
if (e.BytesReceived <= ApkBytesTotalLength)
{
Application.RunOnMainThread(() =>
{
SetDownLoadBtnVisible();
updatingBtn.Text = $"{ Language.StringByID(R.MyInternationalizationString.Updating)} {(int)(e.BytesReceived / (float)ApkBytesTotalLength * 100)}%";
});
}
}
///
/// Client_UploadCompleted
///
///
///
void Client_UploadCompleted(object sender, UploadDataCompletedEventArgs e)
{
System.Console.WriteLine("下载apk完成");
SetDownLoadBtnNoVisible();
}
///
/// 取消下载apk
///
private void CancelDownLoadApkAsync()
{
webClient?.CancelAsync();
SetDownLoadBtnNoVisible();
System.Console.WriteLine("取消下载apk");
}
#endif
}
}