wxr
2020-06-15 b8e94316e41eba72d927d5ca7d931b26139ee8ff
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
using System;
using Android.App;
using Android.Content;
using Android.Database;
using Android.Media;
using Android.Net.Wifi;
using Android.OS;
using Android.Util;
using Android.Widget;
using Java.Util;
using Android.Content.PM;
using Android.Locations;
using Android.Runtime;
using Android.Views;
using Com.Hdl.ON;
//using ICSharpCode.SharpZipLib.Zip;
using Android.Net;
using Android;
using System.Collections.Generic;
using System.Xml;
using Org.XmlPull.V1;
using Android.Support.V4.App;
using Android.Provider;
 
namespace Shared
{
    //[Activity(MainLauncher =true)]  
    //public class BaseActivity1 : Android.App.Activity
    //{
    //    public static Action<BaseActivity1, Android.App.Application> OnCreateActoin;
    //    protected override void OnCreate (Android.OS.Bundle savedInstanceState)
    //    {
    //        base.OnCreate (savedInstanceState);
    //        var mainFrameLayout = new Android.Widget.FrameLayout (this) { KeepScreenOn = true };
    //        SetContentView (mainFrameLayout);
    //        if (OnCreateActoin != null) {
    //            OnCreateActoin (this, this.Application);
    //        }
    //    }
 
 
    //}
    //新的添加,可以解决切换语言后登陆问题。ConfigurationChanges= ConfigChanges.ScreenSize|ConfigChanges.Orientation| ConfigChanges.Keyboard| ConfigChanges.KeyboardHidden| ConfigChanges.Locale,
    [Activity (MainLauncher = true, WindowSoftInputMode = Android.Views.SoftInput.AdjustResize, LaunchMode = LaunchMode.SingleInstance, ConfigurationChanges = ConfigChanges.LayoutDirection | ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden | ConfigChanges.Locale, Theme = "@style/MyTheme", ScreenOrientation = ScreenOrientation.Portrait)]
    public class BaseActivity : Android.App.Activity, ICommon, ViewTreeObserver.IOnGlobalLayoutListener
    {
        enum RequestCode
        {
            ActionLocationSourceSettings = 100,
        }
        WifiManager.MulticastLock multicasetLock;
        public static Action<BaseActivity> MonitorInfoChangedAction;
        public static Action<BaseActivity, Android.App.Application> OnCreateActoin;
        public static Action<BaseActivity> RefreshUIAction;
        public static Action<BaseActivity> OnResumeAction;
        /// <summary>
        /// 网络状态变化
        /// </summary>
        public static Action<int> NetworkStateChanged;
        /// <summary>
        /// Activity 销掉时事件
        /// </summary>
        public static Action<BaseActivity> OnDestroyAction;
        Android.Widget.FrameLayout mainFrameLayout;
        DisplayMetrics metric = new DisplayMetrics ();
        /// <summary>
        /// Y轴坐标
        /// </summary>
        public static int TopMargin;
        public static bool IsHideVirualButtons;
        protected override void OnCreate (Android.OS.Bundle savedInstanceState)
        {
            try {
                Shared.HDLUtils.WriteLine($"Activity 线程ID{System.Threading.Thread.CurrentThread.ManagedThreadId}");
                if (IsHideVirualButtons) {
                    MyJar.Common.HideVirtualButtons (this);
                }
                Shared.Application.Activity = this;
                if (Shared.Application.IsPad) {
                    this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
                }
                base.OnCreate (savedInstanceState);
 
                if (IsHideVirualButtons) {
                    WindowManager.DefaultDisplay.GetRealMetrics (metric);
                } else {
                    WindowManager.DefaultDisplay.GetMetrics (metric);
                }
                //获取设备的宽、高度
                Shared.Application.CurrentWidth = metric.WidthPixels;  //宽度(PX)
                                                                       //考虑到5.7寸屏往上偏移,加高父控件的高度
                Shared.Application.CurrentHeight = metric.HeightPixels - TopMargin;  //高度(PX
 
                //父控件
                var contentView = new Android.Widget.FrameLayout (this) ;
                mainFrameLayout = new Android.Widget.FrameLayout(this) { KeepScreenOn = KeepScreenON } ;
                contentView.AddView (mainFrameLayout, new Android.Widget.FrameLayout.LayoutParams (Shared.Application.CurrentWidth, Shared.Application.CurrentHeight) { TopMargin = TopMargin });
                SetContentView(contentView);
                //界面变化实现的接口
                Window.DecorView.ViewTreeObserver.AddOnGlobalLayoutListener (this);
 
                multicasetLock = WifiManager.FromContext (this).CreateMulticastLock ("WIFI");
                multicasetLock.Acquire ();
                initLanguage ();
 
 
                //启动本地音乐的后台服务
                StartService (new Intent (this, typeof (Other.MusicService)));
                SettingsContentObserver.RegisterVolumeChangeReceiver ();
                //注册广播
                registerReceiver ();
                com.hdl.on.Volume.Init ();
                OnCreateActoin?.Invoke (this, this.Application);
 
                //启动GPS后台服务
                StartGPSService();
                //StartService(new Intent(this, typeof(GPSLocationService)));
 
            } catch { }
        }
        public static bool KeepScreenON = true;
 
        public void StartGPSService()
        {
            try
            {
                StartService(new Intent(this, typeof(GPSLocationService)));
            }
            catch { }
        }
 
        public void StopGpsService()
        {
            try
            {
                StopService(new Intent(this, typeof(GPSLocationService)));
            }
            catch { }
        }
 
 
 
        #region 图库的权限
        Action<bool> imageAction;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetImagePermission(Action<bool> action)
        {
            imageAction = action;
            //如果还没有权限,得请求权限
            if (BuildVersionCodes.M <= Build.VERSION.SdkInt && (CheckSelfPermission(Manifest.Permission.WriteExternalStorage) == Permission.Denied || CheckSelfPermission(Manifest.Permission.ReadExternalStorage) == Permission.Denied))
            {
                RequestPermissions(new string[] { Manifest.Permission.WriteExternalStorage,Manifest.Permission.ReadExternalStorage }, 255);
            }
            else
            {
                //有权限直接回调出去
                if (imageAction != null)
                {
                    imageAction(true);
                    imageAction = null;
                }
            }
        }
        #endregion
        #region 摄像头功能
        Action<bool> cameraAction;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetCamera(Action<bool> action)
        {
            cameraAction = action;
            //如果还没有权限,得请求权限
            if (BuildVersionCodes.M <= Build.VERSION.SdkInt && CheckSelfPermission(Manifest.Permission.Camera) == Permission.Denied)
            {
                RequestPermissions(new string[] { Manifest.Permission.Camera }, 255);
            }
            else
            {
                //有权限直接回调出去
                if (cameraAction != null)
                {
                    cameraAction(true);
                    cameraAction = null;
                }
            }
        }
        #endregion
        #region 获取手机状态信息权限
        Action<bool> readPhoneStateAction;
        /// <summary>
        /// 萤石摄像头那块代码比较特殊,得在调用这个启动他需要的权限
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetPhoneState(Action<bool> action)
        {
            readPhoneStateAction = action;
            //如果还没有权限,得请求权限
            if (BuildVersionCodes.M <= Build.VERSION.SdkInt && (CheckSelfPermission(Manifest.Permission.ReadPhoneState) == Permission.Denied || CheckSelfPermission(Manifest.Permission.CallPhone) == Permission.Denied || CheckSelfPermission(Manifest.Permission.ReadCallLog) == Permission.Denied || CheckSelfPermission(Manifest.Permission.WriteCallLog) == Permission.Denied || CheckSelfPermission(Manifest.Permission.AddVoicemail) == Permission.Denied || CheckSelfPermission(Manifest.Permission.UseSip) == Permission.Denied || CheckSelfPermission(Manifest.Permission.ProcessOutgoingCalls) == Permission.Denied)) {
                RequestPermissions(new string[] { Manifest.Permission.ReadPhoneState, Manifest.Permission.CallPhone, Manifest.Permission.ReadCallLog, Manifest.Permission.WriteCallLog, Manifest.Permission.AddVoicemail, Manifest.Permission.UseSip, Manifest.Permission.ProcessOutgoingCalls }, 255);
            } else {
                //有权限直接回调出去
                if (readPhoneStateAction != null) {
                    readPhoneStateAction(true);
                    readPhoneStateAction = null;
                }
            }
        }
        #endregion
        #region 读写联系人信息
        Action<bool> readWriteContactAction;
        public void ReadWriteContact(Action<bool> action)
        {
            readWriteContactAction = action;
            if (BuildVersionCodes.M <= Android.OS.Build.VERSION.SdkInt && (CheckSelfPermission(Manifest.Permission.ReadContacts) == Permission.Denied || CheckSelfPermission(Manifest.Permission.WriteContacts) == Permission.Denied || CheckSelfPermission(Manifest.Permission.GetAccounts) == Permission.Denied))
            {
                RequestPermissions(new string[] { Android.Manifest.Permission.ReadContacts, Android.Manifest.Permission.WriteContacts, Manifest.Permission.GetAccounts }, 255);
            }
            else
            {
                //有权限直接回调出去
                readWriteContactAction?.Invoke(true);
                readWriteContactAction = null;
            }
        }
        #endregion
        #region 可视对讲的权限
        Action<bool> audioRecordAction;
        public void AudioRecord(Action<bool> action)
        {
            audioRecordAction = action;
            if (BuildVersionCodes.M <= Android.OS.Build.VERSION.SdkInt && CheckSelfPermission(Manifest.Permission.RecordAudio) == Permission.Denied)
            {
                RequestPermissions(new string[] { Manifest.Permission.RecordAudio}, 255);
            }
            else
            {
                //有权限直接回调出去
                if (audioRecordAction != null)
                {
                    audioRecordAction(true);
                    audioRecordAction = null;
                }
            }
        }
        #endregion
 
 
        #region 通用权限请求
        Dictionary<int, Action<bool>> permissionLists = new Dictionary<int, Action<bool>> { };
        int maxCode = 10000;
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetPermission(Action<bool> action,string permission)
        {
            //如果还没有权限,得请求权限
            if (CheckSelfPermission(permission) == Permission.Denied)
            {
                var code = maxCode++;
                permissionLists[code] = action;//根据请求的Code来确认请求的权限
                RequestPermissions(new string[] { permission }, code);
            }
            else
            {
                //有权限直接回调出去
                action?.Invoke(true);
            }
        }
        #endregion
        #region GPS的权限
        Action<bool> gpsLocationAction;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetGPSLocationPermission(Action<bool> action)
        {
            gpsLocationAction = action;
            //如果还没有权限,得请求权限
            if (BuildVersionCodes.M <= Build.VERSION.SdkInt && (CheckSelfPermission(Manifest.Permission.AccessFineLocation) == Permission.Denied || CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) == Permission.Denied))
            {
                RequestPermissions(new string[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation }, 255);
            }
            else
            {
                //有权限直接回调出去
                gpsLocationAction?.Invoke(true);
                gpsLocationAction = null;
 
            }
        }
        #endregion
 
        #region 注册广播事件
        MyBroadcastReceive myBroadcastReceive = new MyBroadcastReceive { };
        void registerReceiver ()
        {
            var intentFilter = new IntentFilter { };
            //监听电话状态变化
            intentFilter.AddAction ("android.intent.action.PHONE_STATE");
            intentFilter.AddAction ("android.intent.action.NEW_OUTGOING_CALL");
            //监听网络变化
            intentFilter.AddAction ("android.net.conn.CONNECTIVITY_CHANGE");
            intentFilter.AddAction ("android.intent.category.DEFAULT");
            //intentFilter.AddCategory
            RegisterReceiver (myBroadcastReceive, intentFilter);
 
            int beforeValue = 10;
            MyBroadcastReceive.ActionIdle = () => {
                var audioManager = (AudioManager)GetSystemService (AudioService);
                int nowValue = (int)(audioManager.GetStreamVolume (Stream.Music) * 100.0f / audioManager.GetStreamMaxVolume (Stream.Music));
                if (com.hdl.on.Volume.VolumeChange != null && beforeValue != nowValue) {
                    com.hdl.on.Volume.VolumeChange (beforeValue);
                }
            };
 
            MyBroadcastReceive.ActioRinging = () => {
                var audioManager = (AudioManager)GetSystemService (AudioService);
                beforeValue = (int)(audioManager.GetStreamVolume (Stream.Music) * 100.0f / audioManager.GetStreamMaxVolume (Stream.Music));
            };
        }
        #endregion
        Action<bool> contactsAction;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Action.</param>
        public void SetContactsPermission(Action<bool> action)
        {
            contactsAction = action;
            //如果还没有权限,得请求权限
            if (BuildVersionCodes.M <= Build.VERSION.SdkInt && CheckSelfPermission(Manifest.Permission.ReadContacts) == Permission.Denied)
            {
                RequestPermissions(new string[] { Manifest.Permission.ReadContacts }, 254);
            }
            else
            {
                //有权限直接回调出去
                contactsAction?.Invoke(true);
                contactsAction = null;
            }
        }
        #region 获取通讯录
         //**版本判断。当手机系统大于 23 时,才有必要去判断权限是否获取**
            
        #endregion
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            //根据Code来确认权限
            if (permissionLists.ContainsKey(requestCode))
            {
                var action = permissionLists[requestCode];
                permissionLists.Remove(requestCode);
                if (0 < grantResults.Length && grantResults[0] == Permission.Granted)
                {
                    action?.Invoke(true);
                }
                else {
                    action?.Invoke(false);
                }
            }
            //之前的写法,后面可以通过上面的方式处理,然后去掉这块代码
            for (int i = 0; i < permissions.Length; i++)
            {
                switch (permissions[i])
                {
                    case Manifest.Permission.AccessFineLocation:
                        if (grantResults[i] == Permission.Granted)
                        {
                            //有权限回调出去
                            gpsLocationAction?.Invoke(true);
                            gpsLocationAction = null;
                        }
                        break;
                    case Android.Manifest.Permission.ReadPhoneState:
                        if (readPhoneStateAction != null)
                        {
                            if (grantResults[i] == Permission.Granted)
                            {
                                readPhoneStateAction(true);
                            }
                            else
                            {
                                readPhoneStateAction(false);
                            }
                            readPhoneStateAction = null;
                        }
                        break;
                    case Manifest.Permission.ReadContacts:
                        if (requestCode == 254) {
                            if (grantResults[i] == Permission.Granted)
                            {
                                contactsAction?.Invoke(true);
                            }
                            else
                            {
                                contactsAction?.Invoke(false);
                            }
                            contactsAction = null;
                        }
                        if (requestCode == 255)
                        {
                            if (grantResults[i] == Permission.Granted)
                            {
                                readWriteContactAction?.Invoke(true);
                            }
                            else
                            {
                                readWriteContactAction?.Invoke(false);
                            }
                            readWriteContactAction = null;
                        }
 
                        break;
                    case Manifest.Permission.RecordAudio:
                        if (audioRecordAction != null)
                        {
                            if (grantResults[i] == Permission.Granted)
                            {
                                audioRecordAction(true);
                            }
                            else
                            {
                                audioRecordAction(false);
                            }
                            audioRecordAction = null;
                        }
                        break;
                    case Manifest.Permission.Camera:
                        if (cameraAction != null)
                        {
                            if (grantResults[i] == Permission.Granted)
                            {
                                cameraAction(true);
                            }
                            else
                            {
                                cameraAction(false);
                            }
                            cameraAction = null;
                        }
                        break;
                    case Manifest.Permission.WriteExternalStorage:
                        if (imageAction != null)
                        {
                            if (grantResults[i] == Permission.Granted)
                            {
                                imageAction(true);
                            }
                            else
                            {
                                imageAction(false);
                            }
                            imageAction = null;
                        }
                        break;
                   
                }
            }
        }
        
 
        protected override void OnResume ()
        {
            base.OnResume ();
            OnResumeAction?.Invoke(this);
        }
 
 
        public override void OnWindowFocusChanged (bool hasFocus)
        {
            base.OnWindowFocusChanged (hasFocus);
            if (hasFocus && null == Shared.Application.RootFrameLayout) {
                initImages (() => {
                    mainFrameLayout.Post (() => {
                        Shared.Application.RootFrameLayout = mainFrameLayout;
                        RefreshUIAction?.Invoke(this);
                    });
                });
            }
        }
        /// <summary>
        ///  审核最后时间
        /// </summary>
        public static DateTime VerifyDateTime = DateTime.Now;
        public static Action BackKeyAction;
        public override bool DispatchKeyEvent (Android.Views.KeyEvent e)
        {
            //百度认证要求返回键有效果,加这个是为了审核通过
            //if (DateTime.Now < VerifyDateTime) {
            //    Shared.HDLUtils.WriteLine ("base VerifyDateTime");
            //    VerifyDateTime = DateTime.MinValue;
            //    //return base.DispatchKeyEvent (e);
            //}
            if (e.KeyCode == Android.Views.Keycode.Back && e.Action == Android.Views.KeyEventActions.Down) {
                BackKeyAction?.Invoke ();
            //    Shared.HDLUtils.WriteLine ("BackKeyAction End!!!");
            //    return true;
            }
            return base.DispatchKeyEvent (e);
        }
 
        public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
        {
            if(keyCode== Keycode.Back){
                //Shared.HDLUtils.WriteLine ("OnKeyDown1");
                //不允许结束程序,只是退出到后台
                if (VerifyDateTime == DateTime.MaxValue)
                {
                    //Shared.HDLUtils.WriteLine ("OnKeyDown2");
                    VerifyDateTime = DateTime.MinValue;
                    MoveTaskToBack (false);
                    //} else {
                    //Shared.HDLUtils.WriteLine ("OnKeyDown3");
                    //BackKeyAction ();
                    //return true;
                }
                return true;
            }
            return true;
            //return base.OnKeyDown(keyCode, e);
        }
 
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (requestCode == 0x30)
            {
                if (data == null) {
                    Shared.Contacts.ContactAction?.Invoke(null, null);
                }
                else
                {
                    string phoneNum = null;
                    string contactName = null;
                    // 创建内容解析者
                    var contentResolver = ContentResolver;
                    ICursor cursor = null;
                    if (data.Data != null)
                    {
                        cursor = contentResolver.Query(data.Data, new string[] { "display_name", "data1" }, null, null, null);
                    }
                    while (cursor.MoveToNext())
                    {
                        contactName = cursor.GetString(cursor.GetColumnIndex("display_name"));
                        phoneNum = cursor.GetString(cursor.GetColumnIndex("data1"));
                    }
                    cursor.Close();
                    //  把电话号码中的  -  符号 替换成空格
                    if (phoneNum != null)
                    {
                        phoneNum = phoneNum.Replace("-", " ");
                        // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
                        phoneNum = phoneNum.Replace(" ", "");
                    }
                    Shared.Contacts.ContactAction?.Invoke(contactName, phoneNum);
                }
            }
        }
 
        protected override void OnDestroy ()
        {
            base.OnDestroy();
 
            OnDestroyAction?.Invoke(this);
            //关闭本地音乐提供的服务
            StopService (new Intent (this, typeof (Other.MusicService)));
            //关闭GPS获取定位服务
            StopGpsService();
 
            if (multicasetLock != null) {
                multicasetLock.Release ();
            }
            //移除手机状态广播
            UnregisterReceiver (myBroadcastReceive);
            
            SettingsContentObserver.UnregisterVolumeChangeReceiver ();
 
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
 
            //Java.Lang.JavaSystem.Exit(0);//正常退出App
        }
 
        void initLanguage ()
        {
            Locale l = Locale.Default;
            string language = l.Language;
            if ("zh" == language) {
                Language.CurrentLanguage = "Chinese";
            } else {
                Language.CurrentLanguage = "English";
            }
        }
 
        void writeFiles (string path)
        {
            //创建根目录
            System.IO.Directory.CreateDirectory (System.IO.Path.Combine (Shared.Application.RootPath, path));
            var paths = Assets.List (path);
            foreach (string fileOrFolderPath in paths) {
                var tempString = fileOrFolderPath.ToLower ();
                //系统自带的图
                if (tempString == "license" || tempString == "images" || tempString == "webkit") {
                    continue;
                }
                if (fileOrFolderPath.EndsWith (".zip")) {
                    //decomparessFile (fileOrFolderPath, Shared.IO.FileUtils.RootPath);
                    continue;
                }
                if (tempString.EndsWith (".txt") || tempString.EndsWith (".png") || tempString.EndsWith (".jpg")) {
                    System.IO.Stream inputStream = null;
                    try {
                        //根目录下如果直接是文件的就不需要复制
                        if (path != "") {
                            inputStream = this.Assets.Open (path + "/" + fileOrFolderPath);
                            //写当前文件
                            IO.FileUtils.WriteFileByInputStream (path + "/" + fileOrFolderPath, inputStream);
                        }
 
                    } catch { } finally {
                        if (inputStream != null) {
                            inputStream.Close ();
                        }
                    }
                } else {
                    if (path == "") {
                        writeFiles (fileOrFolderPath);
                    } else {
                        writeFiles (path + "/" + fileOrFolderPath);
                    }
                }
            }
        }
 
        void initImages (Action action)
        {
            var version = PackageManager.GetPackageInfo (Application.PackageName, 0).VersionCode;
            System.Threading.Tasks.Task.Run (() => {
                try {
                    var SharedPref = GetSharedPreferences ("PrivateData", Android.Content.FileCreationMode.Private);
                    //判断是否已经初始化图片成功,成功了就不在写
                    if (SharedPref.GetInt ("Version", -1) == version) {
                        return;
                    }
 
                    writeFiles ("");
 
                    //全部初始化后所有的信息后就创建这个文件来标记一下
                    var v = SharedPref.Edit ();
                    v.PutInt ("Version", version);
                    v.Apply ();
                    v.Commit ();
                } catch { } finally {
                    action ();
                }
            });
        }
 
 
        public static Action<MonitorData> ControlMonitorSceneAction;
        public void ControlMonitorScene (MonitorData p0)
        {
            ControlMonitorSceneAction?.Invoke(p0);
        }
 
        public static Action<string, string> MonitorMessagePushAction;
        public void MonitorMessagePush (string p0, string p1)
        {
            MonitorMessagePushAction?.Invoke(p0, p1);
        }
 
        public static Action<MonitorData> MonitorSceneDataAction;
        public void MonitorSceneData (MonitorData p0)
        {
            MonitorSceneDataAction?.Invoke(p0);
        }
 
        public void OnGlobalLayout()
        {
            var rect = new Android.Graphics.Rect();
            mainFrameLayout.GetWindowVisibleDisplayFrame(rect);
 
            var softHeight = metric.HeightPixels - (rect.Bottom - rect.Top);
 
            var tempHeight = EditText.FocusBottom + softHeight - metric.HeightPixels;
            //if (0 < tempHeight) {
            //    mainFrameLayout.SetY (-tempHeight - 10);
            //} else {
            //    mainFrameLayout.SetY (0);
            //}
            if (0 < tempHeight)
            {
                mainFrameLayout.SetY(TopMargin - tempHeight - 10);
            }
            else
            {
                mainFrameLayout.SetY(TopMargin);
            }
 
            //Shared.HDLUtils.WriteLine($"屏幕高度{mainFrameLayout.Height} 输入法高度{softHeight}");
            //当前已经是隐藏状态了
            //if(softHeight<=108){
            if (IsHideVirualButtons)
            {
                MyJar.Common.HideVirtualButtons(this);
            }
            //}
        }
 
        public void MoveToFront() {
            SystemHelper.SetTopApp(this.BaseContext);
        }
 
        ///// <summary>
        ///// 解压文件到指定文件夹
        ///// </summary>
        ///// <param name="sourceFile">压缩文件</param>
        ///// <param name="destinationDirectory">目标文件夹,如果为空则解压到当前文件夹下</param>
        ///// <param name="password">密码</param>
        ///// <returns></returns>
        //public bool decomparessFile (string filePath, string destinationDirectory, string password = null)
        //{
        //    bool result = false;
        //    var bufferSize = 1024;
 
        //    try {
        //        if (!System.IO.Directory.Exists (destinationDirectory)) {
        //            System.IO.Directory.CreateDirectory (destinationDirectory);
        //        }
 
        //        using (var zipStream = new ZipInputStream (Assets.Open (filePath))) {
        //            zipStream.Password = password;
        //            var zipEntry = zipStream.GetNextEntry ();
 
        //            while (zipEntry != null) {
        //                if (zipEntry.IsDirectory)//如果是文件夹则创建
        //                {
        //                    System.IO.Directory.CreateDirectory (System.IO.Path.Combine (destinationDirectory,
        //                                                                                 System.IO.Path.GetDirectoryName (zipEntry.Name)));
        //                } else {
        //                    string fileName = System.IO.Path.GetFileName (zipEntry.Name);
        //                    if (!string.IsNullOrEmpty (fileName) && fileName.Trim ().Length > 0) {
        //                        var fileItem = new System.IO.FileInfo (System.IO.Path.Combine (destinationDirectory, zipEntry.Name));
        //                        using (var writeStream = fileItem.Create ()) {
        //                            var buffer = new byte [bufferSize];
        //                            int readLength = 0;
 
        //                            do {
        //                                readLength = zipStream.Read (buffer, 0, bufferSize);
        //                                writeStream.Write (buffer, 0, readLength);
        //                            } while (readLength == bufferSize);
 
        //                            writeStream.Flush ();
        //                            writeStream.Close ();
        //                        }
        //                        fileItem.LastWriteTime = zipEntry.DateTime;
        //                    }
        //                }
        //                zipEntry = zipStream.GetNextEntry ();//获取下一个文件
        //            }
        //            zipStream.Close ();
        //        }
        //        result = true;
        //    } catch (System.Exception ex) {
        //        Shared.HDLUtils.WriteLine ($"文件解压发生错误:{ex}");
        //    }
 
        //    return result;
        //}
    }
 
    /// <summary>
    /// 监听音量的变化
    /// </summary>
    class SettingsContentObserver : ContentObserver
    {
        static SettingsContentObserver settingsContentObserver;
        static Context context;
        public SettingsContentObserver(Context c, Handler handler) : base(handler)
        {
            context = c;
        }
        public override void OnChange(bool selfChange)
        {
            base.OnChange(selfChange);
            if(MyBroadcastReceive.IsCalling){
                return;
            }
            var audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
            float currentVolume = audioManager.GetStreamVolume(Stream.Music) * 100.0f / audioManager.GetStreamMaxVolume(Stream.Music);
            if (com.hdl.on.Volume.VolumeChange != null)
            {
                Shared.HDLUtils.WriteLine ($"媒体音量变化Volume:{currentVolume}");
                com.hdl.on.Volume.VolumeChange((int)currentVolume);
            }
        }
 
        public static void RegisterVolumeChangeReceiver()
        {
            settingsContentObserver = new SettingsContentObserver(Shared.Application.Activity, new Handler());
            context.ContentResolver.RegisterContentObserver(Android.Provider.Settings.System.ContentUri, true, settingsContentObserver);
        }
        public static void UnregisterVolumeChangeReceiver()
        {
            context.ContentResolver.UnregisterContentObserver(settingsContentObserver);
        }
    }
 
    internal static class SystemHelper
    {
        /**
         * 判断本地是否已经安装好了指定的应用程序包
         *
         * @param packageNameTarget :待判断的 App 包名,如 微博 com.sina.weibo
         * @return 已安装时返回 true,不存在时返回 false
         */
        public static bool AppIsExist(Context context, string packageNameTarget)
        {
            return true;
            //if ("" != packageNameTarget.Trim())
            //{
            //    PackageManager packageManager = context.PackageManager;
            //    var packageInfoList = packageManager.GetInstalledPackages(PackageInfoFlags.MatchUninstalledPackages);
            //    foreach (PackageInfo packageInfo in packageInfoList)
            //    {
            //        var packageNameSource = packageInfo.PackageName;
            //        if (packageNameSource == (packageNameTarget))
            //        {
            //            return true;
            //        }
            //    }
            //}
            //return false;
        }
 
        /**
         * 将本应用置顶到最前端
         * 当本应用位于后台时,则将它切换到最前端
         *
         * @param context
         */
        public static void SetTopApp(Context context)
        {
            if (!isRunningForeground(context))
            {
                /**获取ActivityManager*/
                var activityManager = (ActivityManager)context.GetSystemService(Activity.ActivityService);
 
                /**获得当前运行的task(任务)*/
                var taskInfoList = activityManager.GetRunningTasks(100);
                foreach (ActivityManager.RunningTaskInfo taskInfo in taskInfoList)
                {
                    /**找到本应用的 task,并将它切换到前台*/
                    if (taskInfo.TopActivity.PackageName == (context.PackageName))
                    {
                        activityManager.MoveTaskToFront(taskInfo.Id, 0);
                        break;
                    }
                }
            }
        }
 
        /**
         * 判断本应用是否已经位于最前端
         *
         * @param context
         * @return 本应用已经位于最前端时,返回 true;否则返回 false
         */
         static bool isRunningForeground(Context context)
        {
            var activityManager = (ActivityManager)context.GetSystemService(Activity.ActivityService);
            var appProcessInfoList = activityManager.RunningAppProcesses;
            /**枚举进程*/
            foreach (ActivityManager.RunningAppProcessInfo appProcessInfo in appProcessInfoList)
            {
                if (appProcessInfo.Importance == ActivityManager.RunningAppProcessInfo.ImportanceForeground)
                {
                    if (appProcessInfo.ProcessName == (context.ApplicationInfo.ProcessName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}