wxr
2021-07-01 8ac39f2f962329f30ee61ee8a7abe6d6b5940dd5
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
using System;
using System.Net;
using System.Threading.Tasks;
using Android;
using Android.App;
using Android.Content;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using CN.Jpush.Android.Api;
using HDL_ON;
using Java.Util;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Shared;
 
namespace HDL_ON_Android
{
    /// <summary>
    /// 设定为默认启动的Application
    /// </summary>
    [Android.App.Application]
    public class Application : Android.App.Application, Android.App.Application.IActivityLifecycleCallbacks
    {
        static void reStartApp(Android.App.Application application)
        {
            var intent = new Intent(application, typeof(BaseActivity));
            intent.AddFlags(ActivityFlags.NewTask);
            application.StartActivity(intent);
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
        }
 
        public Application(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip) { }
        public override void OnCreate()
        {
            //注册未处理异常事件
            AppCenter.Start("64ac5859-2cd7-4ef8-a5da-5455e29679ec", typeof(Analytics), typeof(Crashes));
            if (Shared.Application.Activity != null)
            {
                reStartApp(this);
                return;
            }
 
            base.OnCreate();
            RegisterActivityLifecycleCallbacks(this);
 
            initAll();
 
        }
 
 
 
        /// <summary>
        /// 所有初始化全部在这个方法实现
        /// </summary>
        void initAll()
        {
 
            string[] permissions = new string[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.RecordAudio,
            Manifest.Permission.Camera, Manifest.Permission.ProcessOutgoingCalls, Manifest.Permission.GetAccounts};
            //禁止屏幕长亮
            BaseActivity.KeepScreenON = false;
            //隐藏虚拟按键
            BaseActivity.IsHideVirualButtons = true;
            //实现安卓返回按键
            BaseActivity.BackKeyAction = () =>
            {
                try
                {
                    var result = MainPage.LoadEvent_BackAction();
                    switch (result)
                    {
                        case 0:
                            break;
                        case 1:
                        case 2:
                            BaseActivity.VerifyDateTime = DateTime.MaxValue;
                            break;
                        default:
                            BaseActivity.VerifyDateTime = DateTime.MaxValue;
                            break;
                    }
                }
                catch (Exception ex)
                {
                    MainPage.Log(ex.Message);
                    BaseActivity.VerifyDateTime = DateTime.MaxValue;
                }
            };
 
            init();
            BaseActivity.OnCreateActoin += (activity, application) =>
            {
                Language.CurrentLanguage = "Chinese";
                Locale locale1 = Locale.Default;
                var localeList = Resources.Configuration.Locale;
                if (localeList.Language == "zh")
                {
                    Language.CurrentLanguage = "Chinese";
                }
                else
                {
                    Language.CurrentLanguage = "English";
                }
                //获取极光推送ID
                GetJPushRegistrationID(activity);
 
                BaseActivity.NetworkStateChanged += (int internetStatus) =>
                {
                    //if (!IsEnterBackground)
                    //{
                    //    ////BusSocket.Stop();
                    //    //new System.Threading.Thread(() =>
                    //    //{
                    //    //    System.Threading.Thread.Sleep(1000);
                    //    //    //BusSocket.Start();
                    //    //})
                    //    //{ IsBackground = true }.Start();
 
                    //}
                    //else
                    //{
                    //    Console.WriteLine("HHH 网络变化但处于后台");
                    //}
 
                    //网络变化处理
                    HDLCommon.Current.UpdateInternetStatus((int)internetStatus, MainPage.IsEnterBackground);
                };
                //开启定位服务
                Shared.Application.StartGPSLocationService();
            };
            BaseActivity.RefreshUIAction += (activity) =>
            {
                MainPage.Show();
                checkSomeInfo();
            };
            BaseActivity.OnResumeAction += (activity) =>
            {
                checkSomeInfo();
 
 
            };
            BaseActivity.OnDestroyAction += (activity) =>
            {
                Console.WriteLine("OnDestroyAction");
                //BusSocket.Stop();
                //UserInfo.Current.unlockTime = DateTime.Now;
            };
 
 
 
            HDLUtils.SetAuthoritiesName("com.hdl.onpro.fileProvider");
 
            //Shared.Application.IsGpsEnable = true;
            //获取经纬度 
            Shared.Application.LocationAction = (lon, lat) =>
            {
                try
                {
                    Shared.Application.LocationAction = null;
                    new HDL_ON.DAL.Server.HttpServerRequest().GetCityInfo(lon.ToString(), lat.ToString());
                    //关闭定位服务
                    Shared.Application.StopGPSLocationService();
                }
                catch (Exception ex)
                {
                    Utlis.WriteLine("GetCityInfo catch" + ex.Message);
                }
                MainPage.Log($"经纬度:::{lon}:{lat}");
            };
 
 
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="activity"></param>
        void GetJPushRegistrationID(BaseActivity activity)
        {
 
            try
            {
 
                //保存获取的极光服务器上的注册ID到本地文件
                var tokenID = JPushInterface.GetRegistrationID(activity);
                Console.WriteLine("RegistrationID:  " + tokenID);
                if (!string.IsNullOrEmpty(tokenID) && OnAppConfig.Instance.PushDeviceToken != tokenID)
                {
                    OnAppConfig.Instance.PushDeviceToken = tokenID;
                    OnAppConfig.Instance.PhoneName = Android.OS.Build.Manufacturer;
                    OnAppConfig.Instance.SaveConfig();
                }
                int loadTokenCount = 0;
                System.Threading.Tasks.Task.Run(() =>
                {
                    while (string.IsNullOrEmpty(tokenID))
                    {
                        System.Threading.Thread.Sleep(1000);
                        tokenID = JPushInterface.GetRegistrationID(activity);
                        Console.WriteLine("Sleep.tokenID + " + JPushInterface.GetRegistrationID(activity));
                        loadTokenCount++;
                        if (loadTokenCount > 30)
                        {
                            break;
                        }
                    }
                    Console.WriteLine("RegistrationID:  " + tokenID);
                    if (!string.IsNullOrEmpty(tokenID) && OnAppConfig.Instance.PushDeviceToken != tokenID)
                    {
                        OnAppConfig.Instance.PushDeviceToken = tokenID;
                        OnAppConfig.Instance.PhoneName = Android.OS.Build.Manufacturer;
                        OnAppConfig.Instance.SaveConfig();
                    }
                });
 
            }
            catch
            {
 
            }
        }
 
        public static bool IsShowTip = true;
        void init()
        {
            //手机名称 Android.OS.Build.Manufacturer;
            //OnAppConfig.Instance.PhoneName = Android.OS.Build.Manufacturer;
//#if DEBUG
            //CN.Jpush.Android.Api.JPushInterface.SetDebugMode(true);
//#endif
            CN.Jpush.Android.Api.JPushInterface.Init(this);
 
        }
        void checkSomeInfo()
        {
            try
            {
                IsShowTip = true;
                var status = isNetworkAvailable(this);
                int internetStatus = 0;
                if (!status)
                {
                    internetStatus = 0;
                }
 
                var isWifi = isWifiConnected(this);
                if (isWifi)
                {
                    internetStatus = 2;
                }
                else
                {
                    internetStatus = 1;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"android check some info erorr : {ex.Message}");
            }
        }
 
        bool isNetworkAvailable(Context context)
        {
            var cm = (ConnectivityManager)context.GetSystemService(ConnectivityService);
            if (cm == null || cm.ActiveNetworkInfo == null)
            {
                return false;
            }
            else
            {
                return cm.ActiveNetworkInfo.IsAvailable;
            }
        }
 
        bool isWifiConnected(Context context)
        {
            if (context != null)
            {
                var mConnectivityManager = (ConnectivityManager)context.GetSystemService
                (ConnectivityService);
                var mWiFiNetworkInfo = mConnectivityManager.GetNetworkInfo(ConnectivityType.Wifi);
                if (mWiFiNetworkInfo != null)
                {
                    return mWiFiNetworkInfo.IsAvailable;
                }
            }
            return false;
        }
 
        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
 
        }
 
        public void OnActivityDestroyed(Activity activity)
        {
            //throw new NotImplementedException ();
        }
 
        public void OnActivityPaused(Activity activity)
        {
            //throw new NotImplementedException ();
        }
 
        public void OnActivityResumed(Activity activity)
        {
            //throw new NotImplementedException ();
        }
 
        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
            //throw new NotImplementedException ();
        }
 
        public void OnActivityStarted(Activity activity)
        {
            //throw new NotImplementedException ();
 
            mCount++;
            if (mCount == 1)
            {
                Console.WriteLine("HHH OnActivityStarted:foreground");
                BusSocketStart();
                //后台回到前台
                new HDL_ON.UI.AppUnlockPage().LoadPage();
            }
        }
 
        public void OnActivityStopped(Activity activity)
        {
 
            mCount--;
            if (mCount == 0)
            {
                Console.WriteLine("HHH OnActivityStopped: background");
                BusSocketStop();
                //进入后台
                UserInfo.Current.unlockTime = DateTime.Now;
 
            }
        }
 
 
        public override void OnTerminate()
        {
            base.OnTerminate();
            UnregisterActivityLifecycleCallbacks(this);
        }
 
        int mCount;
 
        ///// <summary>
        ///// 是否进入后台
        ///// </summary>
        //public bool IsEnterBackground = false;
 
        /// <summary>
        /// 进入后台的时间
        /// </summary>
        DateTime CloseTime = DateTime.Now;
 
        /// <summary>
        /// BusSocketStop
        /// </summary>
        void BusSocketStop()
        {
            //IsEnterBackground = true;
            CloseTime = DateTime.Now;
            MainPage.IsEnterBackground = true;
            //进入后台mqtt正在连接重置状态
            HDL_ON.DAL.Mqtt.MqttClient.RemoteMqttIsConnecting = false;
            HDL_ON.DriverLayer.UdpSocket._BusSocket.Stop();
 
        }
 
        /// <summary>
        /// BusSocketStart
        /// </summary>
        void BusSocketStart()
        {
            //IsEnterBackground = false;
 
            if (CloseTime.AddSeconds(10) < DateTime.Now)
            {
                //后台超过10s就断开MQTT重连
                //if (HDL_ON.DriverLayer.Control.Ins.IsRemote)
                {
                    HDL_ON.DAL.Mqtt.MqttClient.DisConnectRemote("closeTime", false);
                }
            }
 
            MainPage.IsEnterBackground = false;
            HDL_ON.DriverLayer.UdpSocket._BusSocket.Start();
            HDL_ON.DriverLayer.Control.Ins.SearchLoaclGateway();
        }
 
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
 
    }
 
}