黄学彪
2020-12-17 9f326f4000847e6167d8166fa2f6a66f53cb3734
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
using Android.App;
using Android.Widget;
using Android.OS;
using Shared;
using Android.Content.PM;
using System;
using Android.Content;
using Android.Net;
using Shared.Phone.UserView;
using CN.Jpush.Android.Api;
using CN.Jpush.Android.Service;
using Org.Json;
 
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Com.Tencent.MM.Sdk.Openapi;
using ZXing.Mobile;
using System.IO;
 
namespace com.hdl.home
{
    [Activity(Name = "com.hdl.home.wxapi.WXEntryActivity", Exported = true, Theme = "@android:style/Theme.Translucent", LaunchMode = Android.Content.PM.LaunchMode.SingleTask)]
    class WXEntryActivity : Android.App.Activity, IWXAPIEventHandler
    {
        public void OnReq(BaseReq p0)
        {
 
        }
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            Intent = intent;
            com.hdl.home.Application.api?.HandleIntent(intent, this);
            //Finish();
        }
        public static Action<string> RespAction;
        public void OnResp(BaseResp p0)
        {
 
            if (p0 is SendAuth.Resp)
            {
                var resp = p0 as SendAuth.Resp;
 
                switch (resp.ErrCode)
                {
                    case SendAuth.Resp.InnerErrCode.ErrOk:
                        var result = new System.Net.WebClient { }.DownloadString($"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2ec8f53f6fa36e82&secret=a08585cd6ff2ce64570b9e7e6525dd8e&code={resp.Token}&grant_type=authorization_code");
                        RespAction?.Invoke(result);
                        break;
                    default:
                        RespAction?.Invoke(null);
                        break;
 
                        //case SendAuth.Resp.InnerErrCode.ErrUserCancel:
                        //    break;
                        //case SendAuth.Resp.InnerErrCode.ErrAuthDenied:
                        //    break;
 
                }
            }
 
            this.Finish();
        }
        //IWXAPI api;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // 通过WXAPIFactory工厂,获取IWXAPI的实例
            //api = WXAPIFactory.CreateWXAPI(this, "wx2ec8f53f6fa36e82", false);
 
            // 将应用的appId注册到微信
            //api.RegisterApp("wx2ec8f53f6fa36e82");
 
            com.hdl.home.Application.api?.HandleIntent(Intent, this);
        }
    }
    /// <summary>
    /// 设定为默认启动的Application
    /// </summary>
    [Android.App.Application]
    public class Application : Android.App.Application
    {
        public Application(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip) { }
 
        /// <summary>
        /// 检测内存泄露的东西
        /// </summary>
        ///private Square.LeakCanary.RefWatcher _refWatcher;
 
        public override void OnCreate()
        {
            //如果不是App的主进程,则不需要处理
            if (this.IsCurrentAppProcess == false)
            {
                base.OnCreate();
                return;
            }
            try
            {
                //这个东西好像可能会出异常
                this.initAll();
            }
            catch (Exception ex)
            {
                //调试:记录系统异常
                Shared.Phone.HdlLogLogic.Current.WriteOtherText(Shared.Phone.HdlFileNameResourse.LogDirectory, ex.Message + "\r\n" + ex.StackTrace, true, false);
            }
            base.OnCreate();
            // 通过WXAPIFactory工厂,获取IWXAPI的实例
            //api = WXAPIFactory.CreateWXAPI(this, "wx2ec8f53f6fa36e82", true);
 
            //检测内存泄露的东西
            //if (Square.LeakCanary.LeakCanaryXamarin.IsInAnalyzerProcess(this) == false)
            //{
            //    _refWatcher = Square.LeakCanary.LeakCanaryXamarin.Install(this);
            //    _refWatcher.Watch(this);
            //}
 
            // 将应用的appId注册到微信
            api?.RegisterApp("wx2ec8f53f6fa36e82");
        }
 
        /// <summary>
        /// 判断当前进程是不是App自己的主进程
        /// </summary>
        private bool IsCurrentAppProcess
        {
            get
            {
                var activityManager = (ActivityManager)GetSystemService(ActivityService);
                var listProcess = activityManager.RunningAppProcesses;
                foreach (var process in listProcess)
                {
                    if (process.ProcessName == "com.evoyo.home" && process.Pid == Android.OS.Process.MyPid())
                    {
                        return true;
                    }
                }
                return false;
            }
        }
 
        internal static IWXAPI api;
 
        public static void WXLogin()
        {
            var req = new SendAuth.Req { Scope = "snsapi_userinfo", State = "ZigbeeApp" };
            api?.SendReq(req);
        }
 
        /// <summary>
        /// 所有初始化全部在这个方法实现
        /// </summary>
        void initAll()
        {
            //取消屏幕常亮
            BaseActivity.KeepScreenON = false;
            //隐藏底部软按键
            BaseActivity.IsHideVirualButtons = true;
 
            //设置极光调试模式,为false时只打印警告信息
            // System.Console.WriteLine($"AAA : {System.DateTime.Now.ToString()}");
#if Release
            JPushInterface.SetDebugMode(false);
            //保存手机名称到本地文件
            //System.Console.WriteLine($"BBB : {System .DateTime .Now .ToString ()}");
 
            JPushInterface.Init(this);
            //System.Console.WriteLine($"CCC : {System.DateTime.Now.ToString()}");
#endif
 
 
            BaseActivity.BackKeyAction = () =>
            {
                try
                {
                    if (Shared.Common.Config.Instance.BackKeyCanClick == false)
                    {
                        //不允许按返回键
                        return;
                    }
                    if (Shared.Common.CommonPage.Loading != null)
                    {
                        Console.WriteLine(Shared.Common.CommonPage.Loading.CurStatus);
                        if (Shared.Common.CommonPage.Loading.CurStatus)
                        {
                            //Shared.SimpleControl.MainPage.Loading.Hide ();
                            return;
                        }
                    }
                    var lastView = Shared.Application.MainPage.GetChildren(Shared.Application.MainPage.ChildrenCount - 1);
                    if (lastView != null && lastView.Tag?.ToString() == "Dialog")
                    {
                        Console.WriteLine("Remove Dialog!!!!");
                        var lastView2 = Shared.Application.MainPage.GetChildren(Shared.Application.MainPage.ChildrenCount - 2);
                        lastView.RemoveFromParent();
                        lastView2.RemoveFromParent();
                        Console.WriteLine("Remove Dialog End!!!!");
                        return;
                    }
                }
                catch (System.Exception ezx)
                {
                    Console.WriteLine(ezx.Message);
                }
                if (HomePage.Instance.ChildrenCount > 1)
                {
                    Console.WriteLine("Remove PageLayout Children!!!!");
                    HomePage.Instance.GetChildren(HomePage.Instance.ChildrenCount - 1).RemoveFromParent();
                    Console.WriteLine("Remove PageLayout Children End!!!!");
                }
                else if (Shared.Common.CommonPage.Instance.ChildrenCount > 2)
                {
                    //这里只对应登陆界面的
                    Shared.Common.CommonPage.Instance.GetChildren(Shared.Common.CommonPage.Instance.ChildrenCount - 1).RemoveFromParent();
                }
                else
                {
                    BaseActivity.VerifyDateTime = DateTime.MaxValue;
                    Console.WriteLine("BaseActivity VerifyDateTime Max!!!!");
                }
            };
            BaseActivity.OnCreateActoin += (activity, application) =>
            {
                Shared.Application.FontSize = 12;
                AppCenter.Start("4802834a-e7e9-4dd8-93f1-c2f88f0bd464", typeof(Analytics), typeof(Crashes));
#if DEBUG
                //测试ID,瞎写的
                Shared.Common.Config.Instance.RegistrationID = "93f1c2f88f0bd464";
#endif
#if Release
                //保存获取的极光服务器上的注册ID到本地文件
                var registrationId = JPushInterface.GetRegistrationID(activity);
                System.Console.WriteLine("registrationId-极光id=" + registrationId);
                if (!string.IsNullOrEmpty(registrationId))
                {
                    Shared.Common.Config.Instance.RegistrationID = registrationId;
                    Shared.Common.Config.Instance.Save();
                }
                //调试:记录极光ID
                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteOtherText(Shared.Phone.UserCenter.DirNameResourse.JiguangFile, "receive1:" + registrationId, true, true);
#endif
            };
            BaseActivity.RefreshUIAction += (activity) =>
            {
                Shared.Language.CurrentLanguage = "Chinese";
                Shared.Common.CommonPage.Instance.Show();
            };
            BaseActivity.NetworkStateChanged += (v) =>
            {
            };
            BaseActivity.OnDestroyAction += (activity) =>
            {
                //socket停止连接
                //ZigBee.Device.ZbGateway.FindGateWaySocket.Stop();
            };
            HDLUtils.SetAuthoritiesName("com.evoyo.home.fileProvider");
        }
        public static bool IsShowTip = true;
        JpushNotificationReceiver myReceiver = new JpushNotificationReceiver { };
        /// <summary>
        /// 项目启动时网络查询
        /// </summary>
        void checkSomeInfo()
        {
            var status = isNetworkAvailable(this);
            string internetStatus = "Available";
            if (!status)
            {
                internetStatus = "UnaVailable";
            }
            else
            {
                var isWifi = isWifiConnected(this);
                if (isWifi)
                {
                    internetStatus = "WiFiConnect";
                }
                else
                {
                    internetStatus = "MobileConnect";
                }
            }
            int connectState = 0;
            if (internetStatus == "UnaVailable")
            {
                connectState = 0;
            }
            else if (internetStatus == "WiFiConnect")
            {
                connectState = 2;
            }
            else
            {
                connectState = 1;
            }
            //ZigBee.Device.ZbGateway.CheckConnection(connectState);
        }
        /// <summary>
        /// 网络是否可用
        /// </summary>
        /// <returns><c>true</c>, if network available was ised, <c>false</c> otherwise.</returns>
        /// <param name="context">Context.</param>
        bool isNetworkAvailable(Context context)
        {
            var cm = (ConnectivityManager)context.GetSystemService(ConnectivityService);
            if (cm == null || cm.ActiveNetworkInfo == null)
            {
                //当前网络不可用
                return false;
            }
            else
            {
                return cm.ActiveNetworkInfo.IsAvailable;
            }
        }
        /// <summary>
        /// 网络是否连接
        /// </summary
        /// <returns><c>true</c>, if wifi connected was ised, <c>false</c> otherwise.</returns>
        /// <param name="context">Context.</param>
        bool isWifiConnected(Context context)
        {
            if (context != null)
            {
                var cm = (ConnectivityManager)context.GetSystemService(ConnectivityService);
                var mWiFiNetworkInfo = cm.GetNetworkInfo(ConnectivityType.Wifi);
                if (Android.Net.NetworkInfo.State.Connected == mWiFiNetworkInfo.GetState())
                {
                    //当前网络是Wi-Fi连接
                    return true;
                }
                var moWiFiNetworkInfo = cm.GetNetworkInfo(ConnectivityType.Mobile);
                if (Android.Net.NetworkInfo.State.Connected == moWiFiNetworkInfo.GetState())
                {
                    //当前网络是Mobile连接
                    return false;
                }
            }
            return false;
        }
 
 
    }
 
    [BroadcastReceiver(Name = "com.evoyo.home.JpushNotificationReceiver", Exported = false, Enabled = true)]
    [IntentFilter(new string[] { "cn.jpush.android.intent.REGISTRATION",
               "cn.jpush.android.intent.MESSAGE_RECEIVED",
                "cn.jpush.android.intent.NOTIFICATION_RECEIVED",
                "cn.jpush.android.intent.NOTIFICATION_OPENED",
                "cn.jpush.android.intent.CONNECTION"  }, Categories = new string[] { "com.evoyo.home" })]
    public class JpushNotificationReceiver : BroadcastReceiver
    {
        private static string TAG = "JpushNotificationReceiver";
        private NotificationManager nm;
        static string ACTION = "android.intent.action.BOOT_COMPLETED";
        public override void OnReceive(Context context, Intent intent)
        {
            if (nm == null)
            {
                nm = (NotificationManager)context.GetSystemService(Context.NotificationService);
            }
            //base.OnReceive (context, intent);
            try
            {
                Bundle bundle = intent.Extras;
                if (intent.Action == ACTION)
                {
                    //开机自动服务自动启动,PushService是要启动的服务
                    Intent service = new Intent(context, typeof(PushService));
                    context.StartService(service);
                }
 
                //接收Registration Id
                if (JPushInterface.ActionRegistrationId == intent.Action)
                {
                    string regId = bundle.GetString(JPushInterface.ExtraRegistrationId);
                    if (!string.IsNullOrEmpty(regId))
                    {
                        Shared.Common.Config.Instance.RegistrationID = regId;
                    }
#if Release
                    //调试:记录极光ID
                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteOtherText(Shared.Phone.UserCenter.DirNameResourse.JiguangFile, "receive2:" + regId, false, true);
#endif
                }
                //用户点击打开了通知
                else if (JPushInterface.ActionNotificationOpened == intent.Action)
                {
                    OpenNotification(context, bundle);
                }
                //接受到推送下来的通知
                else if (JPushInterface.ActionNotificationReceived == intent.Action)
                {
                    //int notifactionId = bundle.GetInt(JPushInterface.ExtraNotificationId);
                    ReceivingNotification(context, bundle);
                    //Shared.Common.CommonPage.Instance.SingOut();
                }
                //接收到推送下来的自定义消息
                else if (JPushInterface.ActionMessageReceived == intent.Action)
                {
                    bundle.GetString(JPushInterface.ExtraMessage);
                }
                else
                {
                }
            }
            catch (System.Exception e)
            {
 
                System.Console.WriteLine("极光推送出错:" + e.Message);
            }
        }
        /// <summary>
        /// 接收消息通知
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="bundle">Bundle.</param>
        private void ReceivingNotification(Context context, Bundle bundle)
        {
            String title = bundle.GetString(JPushInterface.ExtraNotificationTitle);
            System.Console.WriteLine(TAG, " title : " + title);
            String message = bundle.GetString(JPushInterface.ExtraAlert);
            System.Console.WriteLine(TAG, "message : " + message);
            String extras = bundle.GetString(JPushInterface.ExtraExtra);
            System.Console.WriteLine(TAG, "extras : " + extras);
 
            //处理极光消息推送的逻辑函数
            Shared.Phone.HdlJiguangMsgPushLogic.Current.AdjustJiguangMsgPush(title, message, extras);
        }
        /// <summary>
        /// 打开消息显示界面
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="bundle">Bundle.</param>
        private void OpenNotification(Context context, Bundle bundle)
        {
 
            Intent i = new Intent(context, typeof(BaseActivity));//Intent intent=new Intent( 起始组件对象 , 目标 Service.class);
            i.PutExtras(bundle);
            i.SetFlags(ActivityFlags.NewTask);
            context.StartActivity(i);
 
            String extras = bundle.GetString(JPushInterface.ExtraExtra);
            //String myValue = "";
            try
            {
                VideoMethod(extras);
                //JSONObject extrasJson = new JSONObject(extras);
                //myValue = extrasJson.OptString("myKey");
 
            }
            catch (Exception e)
            {
                System.Console.WriteLine(TAG, "Unexpected: extras is not a valid json", e);
                return;
            }
 
            //if (TYPE_THIS.equals(myValue))
            //{
            //Intent mIntent = new Intent(context, ThisActivity.class);
            //mIntent.putExtras(bundle);
            //mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //context.startActivity(mIntent);
            //}
            //else if (TYPE_ANOTHER.equals(myValue))
            //{
            //Intent mIntent = new Intent(context, AnotherActivity.class);
            //mIntent.putExtras(bundle);
            //mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //context.startActivity(mIntent);
            //}
        }
 
        /// <summary>
        /// android通知栏点击打开可视对讲的方法
        /// </summary>
        /// <param name="hiddenJson">云端推过来的数据</param>
        private void VideoMethod(string hiddenJson)
        {
            var hiddanJson = Newtonsoft.Json.Linq.JObject.Parse(hiddenJson);
            if (hiddanJson == null)
            {
                return;
            }
            var json = Newtonsoft.Json.Linq.JObject.Parse(hiddanJson["HiddanJson"].ToString());
            if (json == null)
            {
                return;
            }
            Shared.Phone.VideoPhone.ESVideoInfo eSVideoInfo = new Shared.Phone.VideoPhone.ESVideoInfo();
            if (json["uuid"].ToString().Contains(","))
            {
                var uuid = json["uuid"].ToString().Split(',');
                eSVideoInfo.ESVideoUUID = uuid[0];
 
            }
            else
            {
                eSVideoInfo.ESVideoUUID = json["uuid"].ToString();
            }
 
            eSVideoInfo.DeviceName = Language.StringByID(Shared.R.MyInternationalizationString.theOutdoorUnit);
            eSVideoInfo.ESRoomID = int.Parse(json["roomno"].ToString());
            if (!string.IsNullOrEmpty(json["unitno"].ToString()))
            {
                string str = json["unitno"].ToString();
                string str1 = str.Substring(0, 2).TrimStart('0');
                string str2 = str.Substring(2, 2).TrimStart('0');
                eSVideoInfo.RoomName = str1 + Language.StringByID(Shared.R.MyInternationalizationString.dong) + str2 + Language.StringByID(Shared.R.MyInternationalizationString.unit);
            }
 
            Shared.Phone.VideoPhone.ESVideo.ShowESvideoVideoIntercom(eSVideoInfo);
 
        }
    }
}
 
namespace Shared
{
    public static class QRCode
    {
        static ZXing.Mobile.MobileBarcodeScanner scanner;
        public static void ScanQRcode(Action<string> action, string cancel = "取消", string flashText = "闪光灯", string titleText = "二维码扫描")
        {
            ((BaseActivity)Shared.Application.Activity).SetCamera(async (obj) =>
            {
                if (obj)
                {
                    if (scanner == null)
                    {
                        MobileBarcodeScanner.Initialize(Shared.Application.Activity.Application);
                        var mZXingCustomScanView = new GateWay.Droid.ZXingCustomScanView(Shared.Application.Activity.Application);
                        mZXingCustomScanView.cancelTextView.Text = cancel;
                        mZXingCustomScanView.flashTextView.Text = flashText;
                        mZXingCustomScanView.titleTextView.Text = titleText;
                        var bOn = false;
                        scanner = new ZXing.Mobile.MobileBarcodeScanner()
                        {
                            UseCustomOverlay = true,
                            CustomOverlay = mZXingCustomScanView
                        };
 
                        mZXingCustomScanView.OnCancel += () =>
                        {
 
                            scanner?.Cancel();
                        };
 
                        mZXingCustomScanView.OnTorch += () =>
                        {
                            bOn = !bOn;
                            scanner?.Torch(bOn);
                        };
                    }
 
                    var result = await scanner.Scan();
 
                    if (result != null)
                        action?.Invoke(result.Text);
                    else
                        action?.Invoke(null);
 
                }
                else
                {
                    action?.Invoke(null);
                }
            });
        }
 
        public static byte[] BytesFromText(string text, int width = 300, int height = 300)
        {
            var barcodeWriter = new ZXing.Mobile.BarcodeWriter
            {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = 0
                }
            };
 
            barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
            var bitmap = barcodeWriter.Write(text);
            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);  // this is the diff between iOS and Android
                stream.Position = 0;
                return stream.ToArray();
            }
        }
    }
}