黄学彪
2020-09-22 ade5917841b0fdcb1df7353ef7c56b1a1bdc9282
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Shared.Common;
 
namespace Shared.Phone.UserCenter.Abount
{
    /// <summary>
    /// 关于的画面
    /// </summary>
    public class AbountForm : EditorCommonForm
    {
        #region ◆ 变量____________________________
        /// <summary>
        /// 是否正在更新中
        /// </summary>
        public bool isUpdating;
        /// <summary>
        /// The web client.
        /// </summary>
        public WebClient webClient = new WebClient { };
        /// <summary>
        /// 更新中
        /// </summary>
        public NormalViewControl btnUpdating;
        /// <summary>
        /// distributedMark
        /// </summary>
        public string distributedMark;
        /// <summary>
        /// updateRow
        /// </summary>
        public FrameRowControl rowUpdate;
        /// <summary>
        /// 下载安卓apk的byte长度
        /// </summary>
        public long ApkBytesTotalLength = 0;
 
        #endregion
 
        /// <summary>
        /// 画面显示(底层会固定调用此方法,借以完成画面创建)
        /// </summary>
        public void ShowForm()
        {
            //设置标题信息
            base.SetTitleText(Language.StringByID(R.MyInternationalizationString.uAboutMe));
            //初始化中部控件
            this.InitMiddleFrame();
        }
        /// <summary>
        /// Closes the form.
        /// </summary>
        public override void CloseFormBefore()
        {
#if Android
            SetDownLoadBtnNoVisible();
            CancelDownLoadApkAsync();
            base.CloseFormBefore();
#elif iOS
           base.CloseFormBefore();
#endif
        }
        /// <summary>
        /// 初始化中部控件
        /// </summary>
        private void InitMiddleFrame()
        {
            //头部白色背景
            var frameLogo = new FrameLayoutBase();
            frameLogo.Height = Application.GetRealHeight(484);
            frameLogo.BackgroundColor = ZigbeeColor.Current.GXCBackgroundColor;
            bodyFrameLayout.AddChidren(frameLogo);
            //图标的容器
            var frameLogoBackground = new FrameLayoutBase();
            frameLogoBackground.Y = Application.GetRealHeight(104);
            frameLogoBackground.Width = this.GetPictrueRealSize(167);
            frameLogoBackground.Height = this.GetPictrueRealSize(167);
            frameLogoBackground.Gravity = Gravity.CenterHorizontal;
            frameLogoBackground.BackgroundColor = ZigbeeColor.Current.GXCButtonBlackSelectedColor;
            frameLogoBackground.Radius = (uint)Application.GetRealHeight(37);
            frameLogo.AddChidren(frameLogoBackground);
            //图标
            var btnLogo = new IconViewControl(144);
            btnLogo.UnSelectedImagePath = "Account/Logo_White.png";
            btnLogo.Gravity = Gravity.Center;
            frameLogoBackground.AddChidren(btnLogo);
            //HDL Home
            var btnName = new NormalViewControl(700, 60, true);
            btnName.Y = Application.GetRealHeight(294);
            btnName.Gravity = Gravity.CenterHorizontal;
            btnName.Text = "HDL Home";
            btnName.TextSize = 15;
            btnName.TextColor = ZigbeeColor.Current.GXCTextDeepBlackColor;
            btnName.TextAlignment = TextAlignment.Center;
            frameLogo.AddChidren(btnName);
            //版本号
            var btnVersion = new NormalViewControl(700, 50, true);
            btnVersion.Y = Application.GetRealHeight(366);
            btnVersion.Gravity = Gravity.CenterHorizontal;
            btnVersion.Text = $"{Language.StringByID(R.MyInternationalizationString.VersionCode)} {CommonPage.CodeIDString}";
            btnVersion.TextSize = 12;
            btnVersion.TextColor = ZigbeeColor.Current.GXCTextGrayColor;
            btnVersion.TextAlignment = TextAlignment.Center;
            frameLogo.AddChidren(btnVersion);
            //列表控件
            var listView = new FrameListControl(12);
            listView.Y = frameLogo.Bottom + Application.GetRealHeight(23);
            listView.BackgroundColor = UserCenterColor.Current.White;
            listView.Height = Application.GetRealHeight(500);
            bodyFrameLayout.AddChidren(listView);
            //服务协议
            //var rowService = new FrameRowControl(listView.rowSpace / 2);
            //listView.AddChidren(rowService);
            //rowService.AddLeftCaption(Language.StringByID(R.MyInternationalizationString.SLA), 400);
            //rowService.AddRightArrow();
            //rowService.AddBottomLine();
            //版本更新
            this.rowUpdate = new FrameRowControl(listView.rowSpace / 2);
            listView.AddChidren(rowUpdate);
            rowUpdate.AddLeftCaption(Language.StringByID(R.MyInternationalizationString.UpdateVersion), 400);
            rowUpdate.AddRightArrow();
            var btnRightView = rowUpdate.AddMostRightView("", 400);
            rowUpdate.CanClick = false;
            rowUpdate.ButtonClickEvent += (sender, e) =>
            {
                UpdateVersion();
            };
            //调整桌布高度
            listView.AdjustRealHeight(Application.GetRealHeight(23));
 
            //更新中
            this.btnUpdating = new NormalViewControl(556, 106, true);
            btnUpdating.Y = Application.GetRealHeight(994);
            btnUpdating.Radius = (uint)Application.GetRealHeight(53);
            btnUpdating.BackgroundColor = ZigbeeColor.Current.GXCDailogBackGroundColor;
            btnUpdating.TextID = R.MyInternationalizationString.Updating;
            btnUpdating.TextSize = 15;
            btnUpdating.TextColor = ZigbeeColor.Current.GXCTextWhiteColor;
            btnUpdating.Gravity = Gravity.CenterHorizontal;
            btnUpdating.TextAlignment = TextAlignment.Center;
            bodyFrameLayout.AddChidren(btnUpdating);
 
            //设置进度控件不可见
            this.SetDownLoadBtnNoVisible();
 
            //检测新版本
            HdlThreadLogic.Current.RunThread(async () =>
            {
                var result = await CanUpdateAsync();
                HdlThreadLogic.Current.RunMain(() =>
                {
                    if (result)
                    {
                        //更新最新版
                        btnRightView.TextID = R.MyInternationalizationString.Update;
                        rowUpdate.CanClick = true;
                    }
                    else
                    {
                        btnRightView.TextID = R.MyInternationalizationString.TheAppVersionIsNewest;
                    }
                });
 
            });
        }
 
        /// <summary>
        /// 设置进度控件不可见
        /// </summary>
        private void SetDownLoadBtnNoVisible()
        {
            isUpdating = false;
            btnUpdating.Visible = false;
        }
        /// <summary>
        /// 设置进度控件可见
        /// </summary>
        private void SetDownLoadBtnVisible()
        {
            isUpdating = true;
            btnUpdating.Visible = true;
            rowUpdate.CanClick = false;
        }
 
        /// <summary>
        /// 检查版本
        /// </summary>
        /// <returns></returns>
        private async System.Threading.Tasks.Task<bool> 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.CompareTo(CommonPage.CodeIDString) > 0)
                    {
                        return true;
                    }
                    return false;
                }
                catch
                {
                   return false;
                }
 
#elif Android
            try
            {
                var versionResult = 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
        }
 
        /// <summary>
        /// 更新
        /// </summary>
        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 = 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<long>(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
        /// <summary>
        /// 获取iOS-APP版本信息
        /// </summary>
        /// <returns>The https app version async.</returns>
        public async System.Threading.Tasks.Task<Common.ResponseEntity.ResultPack> 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<Common.ResponseEntity.ResultPack>(Encoding.UTF8.GetString(result));
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 跳转到APP Store
        /// </summary>
        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
 
        /// <summary>
        /// Install the specified context.
        /// </summary>
        /// <param name="context">Context.</param>
        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);
        }
 
        /// <summary>
        /// 获取 Android-APP 版本信息
        /// </summary>
        /// <returns>The https app version async.</returns>
        private Common.ResponseEntity.ApkInfoOBJ RequestHttpsAndroidAppVersionAsync()
        {
            try
            {
                var requestOBJ = new SendDataToServer.GetAndroidApkInfoOBJ
                {
                    Name = "ZigbeeApp",
                    RequestVersion = CommonPage.CodeIDString
                };
                var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(requestOBJ);
                var result = 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<Common.ResponseEntity.ApkInfoRes>(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;
            }
        }
 
        /// <summary>
        /// 下载安装apk
        /// </summary>
        /// <returns>The load apk async.</returns>
        /// <param name="requestUrl">请求链接</param>
        /// <param name="byteData">请求参数</param>
        private System.Threading.Tasks.Task<byte[]> 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
            {
            }
        }
        /// <summary>
        /// apk下载进度
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        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();
                    btnUpdating.Text = $"{ Language.StringByID(R.MyInternationalizationString.Updating)} {(int)(e.BytesReceived / (float)ApkBytesTotalLength * 100)}%";
                });
            }
        }
 
        /// <summary>
        /// Client_UploadCompleted
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Client_UploadCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            System.Console.WriteLine("下载apk完成");
            SetDownLoadBtnNoVisible();
        }
        /// <summary>
        /// 取消下载apk
        /// </summary>
        private void CancelDownLoadApkAsync()
        {
            webClient?.CancelAsync();
            SetDownLoadBtnNoVisible();
            System.Console.WriteLine("取消下载apk");
        }
#endif
 
    }
}