JLChen
2020-06-04 6d55af8792cf8fbef0055e677b900fc352dba9a2
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
using System;
using System.Net;
using System.Text;
using Android;
using Android.Content;
using Android.Net;
using Android.OS;
using CN.Jpush.Android.Api;
using CN.Jpush.Android.Service;
using Java.Util;
using Newtonsoft.Json.Linq;
using Shared;
using Shared.SimpleControl;
using SmartHome;
 
namespace com.hdl.on
{
    /// <summary>
    /// 设定为默认启动的Application
    /// </summary>
    [Android.App.Application]
    public class Application : Android.App.Application
    {
        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 ()
        {
            if (Shared.Application.Activity != null) {
                reStartApp (this);
                return;
            }
 
            base.OnCreate ();
 
            initAll ();
            com.freeview.global.Video.Start ();
        }
        /// <summary>
        /// 所有初始化全部在这个方法实现
        /// </summary>
        void initAll ()
        {
#if wallon
            BaseActivity.TopMargin = -30;
            BaseActivity.IsEnnableGPS = false;
            BaseActivity.VerifyDateTime = DateTime.MaxValue;
            BaseActivity.KeepScreenON = false;
#endif
            Locale locale1 = Locale.Default;
            var localeList = Resources.Configuration.Locale;
            //if(localeList.Language == "zh") {
            //Language.CurrentLanguage = "Chinese";
            //}
 
            string [] permissions = new string [] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.RecordAudio,
            Manifest.Permission.Camera, Manifest.Permission.ProcessOutgoingCalls, Manifest.Permission.GetAccounts};
 
            var version = Build.VERSION.SdkInt + "";
            Console.WriteLine ("Build.VERSION.SdkInt : " + version);
 
            //Android.Support.V4.App.ActivityCompat.RequestPermissions (BaseActivity., permissions, 321);
 
            BaseActivity.BackKeyAction = () => {
                if (Shared.SimpleControl.MainPage.Loading != null) {
                    Console.WriteLine (MainPage.Loading.CurStatus);
                    if (Shared.SimpleControl.MainPage.Loading.CurStatus) {
                        //Shared.SimpleControl.MainPage.Loading.Hide ();
                        return;
                    }
                }
                try {
                    var lastView = Shared.Application.MainPage.GetChildren (Shared.Application.MainPage.ChildrenCount - 1);
                    //Console.WriteLine ("lastView " + lastView);
                    if (lastView != null && lastView.Tag.ToString () == "Dialog") {
                        if (SharedMethod.SharedMethod.CurPageLayout == null) {
                            BaseActivity.VerifyDateTime = DateTime.MaxValue;
                            return;
                        } else {
                            //Console.WriteLine ("Remove Dialog!!!!");
                            var lastView2 = Shared.Application.MainPage.GetChildren (Shared.Application.MainPage.ChildrenCount - 2);
                            lastView.RemoveFromParent ();
                            lastView2.RemoveFromParent ();
                            //Console.WriteLine ("Remove Dialog End!!!!");
                            BaseActivity.VerifyDateTime = DateTime.MinValue;
                            return;
                        }
                    }
                } catch (System.Exception ezx) {
                    Console.WriteLine (ezx.Message);
                }
                if (SharedMethod.SharedMethod.CurPageLayout != null) {
                    if (SharedMethod.SharedMethod.CurPageLayout.ChildrenCount > 1) {
                        //Console.WriteLine ("Remove PageLayout Children!!!!");
                        SharedMethod.SharedMethod.CurPageLayout.GetChildren (SharedMethod.SharedMethod.CurPageLayout.ChildrenCount - 1).RemoveFromParent ();
                        //Console.WriteLine ("Remove PageLayout Children End!!!!");
                        BaseActivity.VerifyDateTime = DateTime.MinValue;
                    } else {
                        //Console.WriteLine ("BaseActivity.VerifyDateTime = DateTime.MaxValue");
                        BaseActivity.VerifyDateTime = DateTime.MaxValue;
                    }
                }
            };
            BaseActivity.IsHideVirualButtons = true;
            ZXing.Mobile.MobileBarcodeScanner.Initialize (this);
            init ();
            BaseActivity.OnCreateActoin += (activity, application) => {
                Microsoft.AppCenter.AppCenter.Start ("7e0ba985-ae3b-4299-9483-b10f4041f8b2", typeof (Microsoft.AppCenter.Analytics.Analytics), typeof (Microsoft.AppCenter.Crashes.Crashes));
                if (!string.IsNullOrEmpty (UserConfig.Instance.SetLanguage)) {
                    Language.CurrentLanguage = UserConfig.Instance.SetLanguage;
                }
                //保存获取的极光服务器上的注册ID到本地文件
#if wallon
#else
                var tokenID = JPushInterface.GetRegistrationID (activity);
                Console.WriteLine ("RegistrationID:  " + tokenID);
                if (!string.IsNullOrEmpty (tokenID) && UserConfig.Instance.tokenID != tokenID) {
                    UserConfig.Instance.tokenID = tokenID;
                    UserConfig.Instance.SaveUserConfig ();
                }
                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) && UserConfig.Instance.tokenID != tokenID) {
                        UserConfig.Instance.tokenID = tokenID;
                        UserConfig.Instance.SaveUserConfig ();
                    }
                });
#endif
 
                BaseActivity.NetworkStateChanged += (int obj) => {
                    MqttCommon.DisConnectRemoteMqttClient ("NetworkStateChanged");
                    Shared.SimpleControl.EquipmentPublicClass.CheckLinkRemote (obj);
                };
 
            };
            BaseActivity.RefreshUIAction += (activity) => {
                MainPage.Show ();
                checkSomeInfo ();
            };
            BaseActivity.OnResumeAction += (activity) => {
                //new System.Threading.Thread (() => {
                //    while (!MainPage.Showed) {
                //        System.Threading.Thread.Sleep (50);
                //    }
                MqttCommon.DisConnectRemoteMqttClient ();
                checkSomeInfo ();
                Console.WriteLine ("Close OnResumeAction!!!");
                WiFiSet.refreshView?.Invoke ();
            };
            BaseActivity.OnDestroyAction += (activity) => {
                Console.WriteLine ("OnDestroyAction");
                BusSocket.Stop ();
            };
        }
        public static bool IsShowTip = true;
        void init ()
        {
            Shared.Application.Skin = UserConfig.Instance.CurrentSkinName;
            SkinStyle.Current.ChangeColor ();
            UserConfig.Instance.phoneName = Android.OS.Build.Manufacturer;
 
            //设置极光调试模式,为false时只打印警告信息
            JPushInterface.SetDebugMode (false);
            JPushInterface.Init (this);//保存手机名称到本地文件
            //获取经纬度
            MainPage.AirQuality = new AirQuality ();
            Shared.Application.LocationAction = (arg1, arg2) => {
                Shared.Application.LocationAction = null;
                System.Threading.Tasks.Task.Run (() => {
                    while (true) {
                        System.Console.WriteLine ("Get Location  GetAirQuality");
                        //获取天气
                        var webClient = new WebClient ();
                        string url = $"https://developer.hdlcontrol.com/Weather/Weather/FindCity/?lon={arg1}&lat={arg2}";
                        string responseString = null;
                        try {
                            responseString = Encoding.UTF8.GetString (webClient.DownloadData (url));
                        } catch (Exception ex) {
                            Console.WriteLine (ex.Message);
                        }
 
                        if (responseString != null) {
                            try {
                                var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (responseString);
                                JObject jt = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject> (revertObj.ResponseData.ToString ());
                                MainPage.AirQuality.city = jt ["City"].ToString ();
                                var cityId = jt ["Cid"].ToString ();
                                url = $"https://developer.hdlcontrol.com/Weather/Weather/GetAirQualityAndWeather/?cid={cityId}";
                                responseString = null;
                                responseString = Encoding.UTF8.GetString (webClient.DownloadData (url));
                                revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (responseString);
                                jt = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject> (revertObj.ResponseData.ToString ());
                                MainPage.AirQuality.airQTemp = jt ["Temperature"].ToString ();
                                MainPage.AirQuality.airQHumidity = jt ["Humidity"].ToString ();
                                MainPage.AirQuality.airQAirPM25 = jt ["PM25"].ToString ();
                                MainPage.AirQuality.airQAirWeather = jt ["Weather"].ToString ();
                                break;
                            } catch (Exception ex) {
                                Console.WriteLine (ex.ToString ());
                            }
                        }
                        System.Threading.Thread.Sleep (1000);
                    }
                    Shared.Application.RunOnMainThread (() => {
                        CommonPage.RefreshAir?.Invoke ();
                    });
                });
            };
        }
        void checkSomeInfo ()
        {
            try {
                RemoteInfo.Current.ReadMsgList (IsShowTip);
                JPushInterface.ClearAllNotifications (this);
 
                IsShowTip = true;
                var status = isNetworkAvailable (this);
                int internetStatus = 0;
                if (!status) {
                    internetStatus = 0;
                }
 
                var isWifi = isWifiConnected (this);
                if (isWifi) {
                    internetStatus = 2;
                } else {
 
                    internetStatus = 1;
                }
                UserConfig.Instance.internetStatus = internetStatus;
                Shared.SimpleControl.EquipmentPublicClass.CheckLinkRemote (internetStatus);
            } 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;
        }
    }
    [BroadcastReceiver]
    [Android.App.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.hdl.in" })
           ]
    public class JpushNotificationReceiver : BroadcastReceiver
    {
        static string ACTION = "android.intent.action.BOOT_COMPLETED";
 
        public override void OnReceive (Context context, Intent intent)
        {
            try {
                Console.WriteLine ("JpushNotificationReceiver" + intent.Action);
 
                Bundle bundle = intent.Extras;
                if (intent.Action == ACTION) {
                    //Console.WriteLine ("开机自动服务自动启动,PushService是要启动的服务  ");
                    var service = new Intent (context, typeof (PushService));
                    context.StartService (service);
                }
                //接收Registration Id
                else if (JPushInterface.ActionRegistrationId == intent.Action) {
                    string regId = bundle.GetString (JPushInterface.ExtraRegistrationId);
                    //System.Console.WriteLine ("Registration ID:" + regId);
                } else if (JPushInterface.ActionNotificationOpened == intent.Action) {
                    Console.WriteLine ("用户点击打开了通知");
                    Application.IsShowTip = false;
 
                    if (Shared.Application.Activity == null) {
                        var tempIntent = new Intent (context, typeof (Shared.BaseActivity));//Intent intent=new Intent( 起始组件对象 , 目标 Service.class);
                        tempIntent.SetFlags (ActivityFlags.BroughtToFront);
                        context.StartActivity (tempIntent);
                    } else {
                        (Shared.Application.Activity as BaseActivity).MoveToFront ();
                        RemoteInfo.Current.ReadMsgList (false);
                    }
                } else {
                    Console.WriteLine ("极光推送!!!");
                    RemoteInfo.Current.ReadMsgList (true);
                }
            } catch (System.Exception e) {
                Console.WriteLine ("极光推送出错:" + e.Message);
            }
        }
    }
}