wxr
2023-09-04 82b67388873fdd2213b00fa212b9e46c0d40e3cf
OnPro/RongAn/AppDelegate.cs
@@ -1,42 +1,409 @@
using Foundation;
using System;
using Foundation;
using HDL_ON;
using Shared;
using UIKit;
using HDL_ON.UI;
using HDL_ON.DAL.Server;
namespace RongAn
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
    [Register ("AppDelegate")]
    public class AppDelegate : UIResponder, IUIApplicationDelegate {
        [Export("window")]
        public UIWindow Window { get; set; }
        [Export ("application:didFinishLaunchingWithOptions:")]
        public bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
    public class AppDelegate : BaseApplicationDelegateForHdlOn// BaseApplicationDelegate
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method
        // class-level declarations
        public override UIWindow Window
        {
            get;
            set;
        }
        //}
        public static UINavigationController rootViewController;
        public static void CleanApplicationIconBadgeNumber()
        {
            UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
        }
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            //byte[] array = new byte[(ulong)deviceToken.Length];
            //System.Runtime.InteropServices.Marshal.Copy(deviceToken.Bytes, array, 0, array.Length);
            //System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            //for (int i = 0; i < array.Length; i++)
            //{
            //    stringBuilder.AppendFormat("{0:x2}", array[i]);
            //}
            //string text = stringBuilder.ToString();
            //if (NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken") != text)
            //{
            //    NSUserDefaults.StandardUserDefaults.SetString(text, "PushDeviceToken");
            //}
            ///// Get current device token
            //var DeviceToken = text;
            //if (!string.IsNullOrWhiteSpace(DeviceToken))
            //{
            //    DeviceToken = DeviceToken.Trim('<').Trim('>').Replace(" ", "");
            //}
            //// Get previous device token
            //var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
            //// Has the token changed?
            //if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
            //{
            //    NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
            //    OnAppConfig.Instance.PushDeviceToken = DeviceToken;
            //    OnAppConfig.Instance.PhoneName = UIDevice.CurrentDevice.Name;
            //    OnAppConfig.Instance.SaveConfig();
            //}
            //if (OnAppConfig.Instance.PushDeviceToken != DeviceToken)
            //{
            //    OnAppConfig.Instance.PushDeviceToken = DeviceToken;
            //    OnAppConfig.Instance.PhoneName = UIDevice.CurrentDevice.Name;
            //    OnAppConfig.Instance.SaveConfig();
            //}
        }
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            //Console.WriteLine("DidReceiveRemoteNotification:" + application.ApplicationState.ToString());
            //Console.WriteLine("推送消息:"+userInfo);
            ////读取推送信息
            //UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
            //if (userInfo == null)
            //{
            //    return;
            //}
            //Console.WriteLine(userInfo);
            ////HDLCommon.Current.ShowAlert("DidReceiveRemoteNotification:" + userInfo.ToString());
            //if (application.ApplicationState == UIApplicationState.Active || application.ApplicationState == UIApplicationState.Background)
            //{
            //    HandleNotificationMessageUserInfo(userInfo, false);
            //}
            //else
            //{
            //    //Inactive
            //    HandleNotificationMessageUserInfo(userInfo, false);
            //}
            //completionHandler(UIBackgroundFetchResult.NewData);
        }
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            if (application.ApplicationState == UIApplicationState.Active)
            {
                Console.WriteLine("ReceivedRemoteNotification1");
            }
            else if (application.ApplicationState == UIApplicationState.Background)
            {
                Console.WriteLine("ReceivedRemoteNotification2");
            }
            else if (application.ApplicationState == UIApplicationState.Inactive)
            {
                Console.WriteLine("ReceivedRemoteNotification3");
            }
        }
        public override void OnResignActivation(UIApplication application)
        {
            Console.WriteLine("OnResignActivation");
            UserInfo.Current.unlockTime = DateTime.Now;
        }
        public override void DidEnterBackground(UIApplication application)
        {
            //进入后台
            BusSocketStop();
            Console.WriteLine("DidEnterBackground");
        }
        public override void WillEnterForeground(UIApplication application)
        {
            //回到前台,处理事件
            BusSocketStart();
            Console.WriteLine("WillEnterForeground");
        }
        public override void WillTerminate(UIApplication application)
        {
            Console.WriteLine("WillTerminate");
        }
        public override void OnActivated(UIApplication application)
        {
            Console.WriteLine("OnActivated");
            base.OnActivated(application);
        }
        /// <summary>
        /// 设置当前使用语言
        /// </summary>
        void SetCurrentLanguage()
        {
            if (string.IsNullOrEmpty(OnAppConfig.Instance.SetLanguage))
            {
                if (NSLocale.PreferredLanguages[0].Contains("zh-"))
                {
                    Language.CurrentLanguage = "Chinese";
                }
                else
                {
                    Language.CurrentLanguage = "English";
                }
            }
            else
            {
                Language.CurrentLanguage = OnAppConfig.Instance.SetLanguage;
            }
        }
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            Console.WriteLine("111111111111");
            SetCurrentLanguage();
            //Shared.Application.FontSize = 12;
            //Bugly.Bugly.StartWithAppId("1dc40c170a");
            //取消EditText默认密码输入方式
            Shared.Application.IsEditTextContentTypePassword = false;
            //默认使用苹方字体
            Shared.Application.IsUsePingFang = true;
            //保持屏幕常亮或者自动锁屏
            application.IdleTimerDisabled = false;
            base.FinishedLaunching(application, launchOptions);
            Window = new UIWindow(UIScreen.MainScreen.Bounds);
            rootViewController = new UINavigationController(new ViewController()) { NavigationBarHidden = true };
            Window.RootViewController = rootViewController;
            Window.MakeKeyAndVisible();
            application.StatusBarStyle = UIStatusBarStyle.DarkContent;
            DealWithPushMes(launchOptions);
            Console.WriteLine("FinishedLaunching");
            return true;
        }
        // UISceneSession Lifecycle
        [Export ("application:configurationForConnectingSceneSession:options:")]
        public UISceneConfiguration GetConfiguration (UIApplication application, UISceneSession connectingSceneSession, UISceneConnectionOptions options)
        /// <summary>
        /// 处理通知消息
        /// </summary>
        void HandleNotificationMessageUserInfo(NSDictionary userInfo, bool bFinishedLaunching)
        {
            // Called when a new scene session is being created.
            // Use this method to select a configuration to create the new scene with.
            return UISceneConfiguration.Create ("Default Configuration", connectingSceneSession.Role);
        }
        [Export ("application:didDiscardSceneSessions:")]
        public void DidDiscardSceneSessions (UIApplication application, NSSet<UISceneSession> sceneSessions)
            try
        {
            // Called when the user discards a scene session.
            // If any sessions were discarded while the application was not running, this will be called shortly after `FinishedLaunching`.
            // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
                if (userInfo.ContainsKey(new NSString("aps")))
                {
                    var aps = userInfo["aps"] as NSDictionary;
                    var alert = aps["alert"] as NSDictionary;
                    var body = alert["body"] as NSString;
                    var title = alert["title"] as NSString;
                    var expandData = "";
                    var messageType = "";
                    var expantContent = "";
                    var homeId = "";
                    if (userInfo.ContainsKey(new NSString("expandData")))
                    {
                        var expandDataStr = userInfo["expandData"] as NSString;
                        if (expandDataStr == null)
                        {
                            var expandDataNSD = userInfo["expandData"] as NSDictionary;
                            if (expandDataNSD != null)
                            {
                                expandData = expandDataNSD.ToString();
                                if (expandDataNSD.ContainsKey(new NSString("messageType")))
                                {
                                    messageType = expandDataNSD["messageType"] as NSString;
                                    Utlis.WriteLine("messageType: " + messageType);
                                }
                                if (expandDataNSD.ContainsKey(new NSString("expantContent")))
                                {
                                    expantContent = expandDataNSD["expantContent"] as NSString;
                                    Utlis.WriteLine("expantContent: " + expantContent);
                                }
                                if (expandDataNSD.ContainsKey(new NSString("homeId")))
                                {
                                    homeId = expandDataNSD["homeId"].ToString();
                                    Utlis.WriteLine("homeId: " + homeId);
                                }
                            }
                        }
                        else
                        {
                            expandData = expandDataStr;
                        }
                    }
                    var pushMes = new JPushMessageInfo()
                    {
                        HomeId = homeId,
                        Title = title,
                        Content = body,
                        Extras = expandData,
                        messageType = messageType,
                        expantContent = expantContent
                    };
                    Utlis.WriteLine("PushMes title : " + pushMes.Title);
                    Utlis.WriteLine("PushMes message : " + pushMes.Content);
                    Utlis.WriteLine("PushMes extras : " + pushMes.Extras);
                    if (!string.IsNullOrEmpty(pushMes.spk))//自研可视对讲需要记录时间反呼
                    {
                        UserInfo.Current.pushMessageInfo = pushMes;
                        UserInfo.Current.inCall = DateTime.Now;
                    }
                    if (bFinishedLaunching)
                    {
                        if (pushMes.Extras != null)
                        {
                            if (pushMes.Extras.Contains("OffLine"))
                            {
                                //haveToSignOut = true;
                                //强制下线
                                UserInfo.Current.LastTime = DateTime.MinValue;
                                UserInfo.Current.headImagePagePath = "LoginIcon/2.png";//重置用户头像
                                UserInfo.Current.SaveUserInfo();
                                HDLCommon.Current.ShowAlert(Language.StringByID(StringId.LoggedOnOtherDevices));
                            }
                            else
                            {
                                //HDLCommon.Current.AdjustPushMessage(pushMes);
                                this.CommonAdjustPushMessage(pushMes);//2023年04月13日15:55:54 修改
                            }
                        }
                    }
                    else
                    {
                        //HDLCommon.Current.AdjustPushMessage(pushMes);
                        this.CommonAdjustPushMessage(pushMes);
                    }
                }
            }
            catch
            {
                //HDLCommon.Current.ShowAlert("catch2222");
            }
        }
        ///// <summary>
        ///// 退出登录标记
        ///// </summary>
        //bool haveToSignOut;
        /// <summary>
        /// 启动APP 处理通知
        /// </summary>
        /// <param name="launchOptions"></param>
        void DealWithPushMes(NSDictionary launchOptions)
        {
            //haveToSignOut = false;
            if (launchOptions != null)
            {
                // check for a remote notification
                if (launchOptions.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
                {
                    NSDictionary userInfo = launchOptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
                    if (userInfo != null)
                    {
                        //HandleNotificationMessageUserInfo(userInfo, true);
                    }
        }
    }
}
        /// <summary>
        /// 进入后台的时间
        /// </summary>
        DateTime CloseTime = DateTime.Now;
        /// <summary>
        /// 进入后台处理时间
        /// BusSocketStop
        /// </summary>
        void BusSocketStop()
        {
            //SharedMethod.SharedMethod.IsBackground = true;
            CloseTime = DateTime.Now;
            MainPage.IsEnterBackground = true;
            //进入后台mqtt正在连接重置状态
            HDL_ON.DAL.Mqtt.MqttClient.RemoteMqttIsConnecting = false;
            HDL_ON.DriverLayer.UdpSocket._BusSocket.Stop();
        }
        /// <summary>
        /// 回到前台,处理事件
        /// </summary>
        void BusSocketStart()
        {
            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();
            //重连mqtt防止mqtt进入假死状态 2023-05-03 22:55:12 wxr
            HDL_ON.DAL.Mqtt.MqttClient.InitState();
            new AppUnlockPage().LoadPage();
            UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
            HDL_ON.DriverLayer.Control.Ins.SearchLoaclGateway();
        }
        public void CommonAdjustPushMessage(JPushMessageInfo pushMes)
        {
            new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                while (MainPage.BasePageView == null)
                {
                    System.Threading.Thread.Sleep(300);
                }
                Shared.Application.RunOnMainThread(() =>
                {
                    HDLCommon.Current.AdjustPushMessage(pushMes);
                });
            })).Start();
        }
    }
}