Esempio n. 1
0
    // Init - Only required method you call to setup OneSignal to recieve push notifications.
	//        Call this on the first scene that is loaded.
	// appId                  = Your OneSignal AppId from onesignal.com
	// googleProjectNumber    = Your Google Project Number that is only required for Android GCM pushes.
	// inNotificationDelegate = Calls this delegate when a notification is opened or one is received when the user is in your game.
	// autoRegister           = Set false to delay the iOS accept notification system prompt. Defaults true.
	//                          You can then call RegisterForPushNotifications at a better point in your game to prompt them.
	public static void Init(string appId, string googleProjectNumber, NotificationReceived inNotificationDelegate, bool autoRegister) {
		#if !UNITY_EDITOR
			#if ONESIGNAL_PLATFORM
				if (initialized) return;
				#if UNITY_ANDROID
					oneSignalPlatform = new OneSignalAndroid(gameObjectName, googleProjectNumber, appId, logLevel, visualLogLevel);
                #elif UNITY_IPHONE
					//oneSignalPlatform = new OneSignalIOS(gameObjectName, appId, autoRegister, logLevel, visualLogLevel);
                #elif UNITY_WP8
					oneSignalPlatform = new OneSignalWP(appId);
                #endif
				notificationDelegate = inNotificationDelegate;
				
                #if !UNITY_WP8
					GameObject go = new GameObject(gameObjectName);
					go.AddComponent<OneSignal>();
					DontDestroyOnLoad(go);
                #endif
				
				initialized = true;
            #endif
        #else
            print("Please run OneSignal on a device to see push notifications.");
		#endif
	}
        public static void Init(string appId, string launchArgs, NotificationReceived inNotificationDelegate = null, ExternalInit inExternalInit = null)
        {
            mAppId       = appId;
            externalInit = inExternalInit;

            if (inNotificationDelegate != null)
            {
                notificationDelegate = inNotificationDelegate;
            }

            mPlayerId   = (string)settings.Values["OneSignalPlayerId"];
            mChannelUri = (string)settings.Values["OneSignalChannelUri"];

            checkForNotificationOpened(launchArgs);


            if (initDone)
            {
                return;
            }

            fallBackOneSignalSession = new Timer(o => { SendSession(null); }, null, 20000, Timeout.Infinite);

            Windows.UI.Core.CoreWindow.GetForCurrentThread().VisibilityChanged += OneSignal_VisibilityChanged_Window_Current;

            lastPingTime = DateTime.Now.Ticks;

            // async
            GetPushUri();

            initDone = true;
        }
Esempio n. 3
0
    // Init - Only required method you call to setup OneSignal to recieve push notifications.
    //        Call this on the first scene that is loaded.
    // appId                  = Your OneSignal AppId from onesignal.com
    // googleProjectNumber    = Your Google Project Number that is only required for Android GCM pushes.
    // inNotificationDelegate = Calls this delegate when a notification is opened or one is received when the user is in your game.
    // autoRegister           = Set false to delay the iOS accept notification system prompt. Defaults true.
    //                          You can then call RegisterForPushNotifications at a better point in your game to prompt them.
    public static void Init(string appId, string googleProjectNumber, NotificationReceived inNotificationDelegate, bool autoRegister)
    {
      #if !UNITY_EDITOR
         #if ONESIGNAL_PLATFORM
        if (initialized)
        {
            return;
        }
            #if UNITY_ANDROID
        oneSignalPlatform = new OneSignalAndroid(gameObjectName, googleProjectNumber, appId, logLevel, visualLogLevel);
            #elif UNITY_IPHONE
        oneSignalPlatform = new OneSignalIOS(gameObjectName, appId, autoRegister, logLevel, visualLogLevel);
            #elif UNITY_WP8
        oneSignalPlatform = new OneSignalWP80(appId);
            #elif UNITY_WP_8_1
        oneSignalPlatform = new OneSignalWPWNS(appId);
            #endif
        notificationDelegate = inNotificationDelegate;

            #if !UNITY_WP8 && !UNITY_WP_8_1
        GameObject go = new GameObject(gameObjectName);
        go.AddComponent <OneSignal>();
        DontDestroyOnLoad(go);
            #endif

        initialized = true;
        #endif
      #else
        print("Please run OneSignal on a device to see push notifications.");
      #endif
    }
        private async Task<DeviceInstallation> GenerateInstallation(string groupName = null)
        {
            App.Channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
            App.Channel.PushNotificationReceived += (s, e) =>
            {
                NotificationReceived?.Invoke(s, e);
            };

            string installationId = null;
            if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("nhInstallationID"))
            {
                installationId = Guid.NewGuid().ToString();
                ApplicationData.Current.LocalSettings.Values.Add("nhInstallationID", installationId);
            }
            else
                installationId = (string)ApplicationData.Current.LocalSettings.Values["nhInstallationID"];

            string userTag = $"{App.User.SID}";
            string deviceTag = $"{installationId}";
            //string userTag = "testtag";

            var deviceInstallation = new DeviceInstallation
            {
                InstallationId = installationId,
                Platform = "wns",
                PushChannel = App.Channel.Uri,
                Tags = groupName == null ? new string[] { userTag, deviceTag } : new string[] { userTag, deviceTag, groupName }
            };

            App.DeviceInstallation = deviceInstallation;
            return deviceInstallation;
        }
Esempio n. 5
0
        private void Client_NotificationReceived(object sender, JsonRpcNotificationEventArgs e)
        {
            if (e.Notification.Method == Methods.Log)
            {
                var logMessage = e.Notification.GetParams <LogMessage>();
                switch (logMessage.level)
                {
                case LogLevel.debug:
                    logger.Debug("Butler: " + logMessage.message);
                    break;

                case LogLevel.info:
                    logger.Info("Butler: " + logMessage.message);
                    break;

                case LogLevel.warning:
                    logger.Warn("Butler: " + logMessage.message);
                    break;

                case LogLevel.error:
                    logger.Error("Butler: " + logMessage.message);
                    break;
                }
            }

            NotificationReceived?.Invoke(this, e);
        }
    public void Notify(string txt, SimulationEventNotificationPriority prio = SimulationEventNotificationPriority.Normal)
    {
        DateTime timestamp = GameTimeComponent.CurrentTime;
        SimulationEventNotification newNotification = new SimulationEventNotification(txt, prio, timestamp);

        NotificationReceived?.Invoke(newNotification);
    }
Esempio n. 7
0
        private void DataReceived(string data)
        {
            var request = Serialization.FromJson <RpcMessage>(data);

            if (request.Id != null && string.IsNullOrEmpty(request.Method))
            {
                // Response
                requestResponses.TryAdd(request.Id.Value, data);
            }
            else if (request.Id != null && !string.IsNullOrEmpty(request.Method))
            {
                // Request
                RequestReceived?.BeginInvoke(this, new JsonRpcRequestEventArgs()
                {
                    Request = Serialization.FromJson <JsonRpcRequest>(data)
                }, EventEndCallback <JsonRpcRequestEventArgs>, null);
            }
            else if (request.Id == null)
            {
                // Notification
                NotificationReceived?.BeginInvoke(this, new JsonRpcNotificationEventArgs()
                {
                    Notification = Serialization.FromJson <JsonRpcNotification>(data)
                }, EventEndCallback <JsonRpcNotificationEventArgs>, null);
            }
            else
            {
                logger.Error("Recevied invalid RPC message:");
                logger.Error(data);
            }
        }
Esempio n. 8
0
    // Init - Only required method you call to setup GameThrive to recieve push notifications.
    //        Call this on the first scene that is loaded.
    // appId                  = Your GameThrive app id from gamethrive.com
    // googleProjectNumber    = Your google project number that is only required for Android GCM pushes.
    // inNotificationDelegate = Calls this delegate when a notification is opened or one is received when the user is in your game.
    // autoRegister           = Set false to delay the iOS accept notification system prompt. Defaults true.
    //                          You can then call RegisterForPushNotifications at a better point in your game to prompt them.
    public static void Init(string appId, string googleProjectNumber, NotificationReceived inNotificationDelegate, bool autoRegister)
    {
                #if !UNITY_EDITOR
                        #if GAMETHRIVE_PLATFORM
        if (initialized)
        {
            return;
        }
                                #if UNITY_ANDROID
        gameThrivePlatform = new GameThriveAndroid(gameObjectName, googleProjectNumber, appId);
                                #elif UNITY_IPHONE
        gameThrivePlatform = new GameThriveIOS(gameObjectName, appId, autoRegister);
                    #elif UNITY_WP8
        gameThrivePlatform = new GameThriveWP(appId);
                                #endif
        notificationDelegate = inNotificationDelegate;

                                #if !UNITY_WP8
        GameObject go = new GameObject(gameObjectName);
        go.AddComponent <GameThrive>();
        DontDestroyOnLoad(go);
                                #endif

        initialized = true;
                        #endif
                #else
        print("Please run GameThrive on a device to see push notifications.");
                #endif
    }
Esempio n. 9
0
        /// <inheritdoc />
        public void Notify(INotification notification)
        {
            NotificationReceived?.Invoke(this, notification);
            var popup = new NotificationPopupViewModel(notification);

            popup.Closed += e =>
            {
                Notifications.Remove(e);
            };

            var timer = new Timer(_notificationDuration);

            timer.Elapsed += delegate
            {
                ExecuteOnUIContext(() =>
                {
                    popup.Close();
                    timer.Stop();
                    timer.Dispose();
                });
            };
            timer.Start();
            GC.KeepAlive(timer);
            Notifications.Add(popup);
        }
        private void ConnectSocket(string uri)
        {
            WebSocket = new WebSocket(uri);
            WebSocket.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            WebSocket.OnMessage += (sender, e) =>
            {
                try
                {
                    var data = JsonConvert.DeserializeObject <NotificationData <JObject> >(e.Data);
                    if (!_typeMap.ContainsKey(data.TopicName.ToLowerInvariant()))
                    {
                        return;
                    }

                    var genericNotificationType  = typeof(NotificationData <>);
                    var specificNotificationType =
                        genericNotificationType.MakeGenericType(_typeMap[data.TopicName.ToLowerInvariant()]);

                    var notification = JsonConvert.DeserializeObject(e.Data, specificNotificationType);
                    if (notification == null)
                    {
                        return;
                    }

                    NotificationReceived?.Invoke((INotificationData)notification);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            };
            WebSocket.Connect();
        }
Esempio n. 11
0
            public TileInfo(string App)
            {
                notificationTimer = new Timer(5000);
                Name  = "App Name (TEMP)";                   //Get App name here
                Icon  = new ImageBrush();                    //Get App icon here
                Color = Color.FromArgb(0xFF, 0xFF, 0, 0xFF); //Get App color here

                //"Microsoft.BingSports_3.0.4.212_x64__8wekyb3d8bbwe"

                CurrentNotification = AppxTools.GetLiveTileNotification(AppxTools.GetUpdateAddressFromApp(App));
                UIElement element = new UIElement();

                notificationTimer.Elapsed += delegate
                {
                    element.Dispatcher.Invoke(new Action(() =>
                    {
                        var NewNotification = AppxTools.GetLiveTileNotification(AppxTools.GetUpdateAddressFromApp(App));
                        if (CurrentNotification != NewNotification)
                        {
                            NotificationReceived?.Invoke(this, new NotificationInfoEventArgs()
                            {
                                OldNotification = CurrentNotification,
                                NewNotification = NewNotification
                            });
                            CurrentNotification = NewNotification;
                        }
                    }));
                };
                notificationTimer.Start();
            }
    // Init - Only required method you call to setup GameThrive to recieve push notifications.
	//        Call this on the first scene that is loaded.
	// appId                  = Your GameThrive app id from gamethrive.com
	// googleProjectNumber    = Your google project number that is only required for Android GCM pushes.
	// inNotificationDelegate = Calls this delegate when a notification is opened or one is received when the user is in your game.
	// autoRegister           = Set false to delay the iOS accept notification system prompt. Defaults true.
	//                          You can then call RegisterForPushNotifications at a better point in your game to prompt them.
	public static void Init(string appId, string googleProjectNumber, NotificationReceived inNotificationDelegate, bool autoRegister) {
		#if !UNITY_EDITOR
			#if GAMETHRIVE_PLATFORM
				if (initialized) return;
				#if UNITY_ANDROID
					gameThrivePlatform = new GameThriveAndroid(gameObjectName, googleProjectNumber, appId);
				#elif UNITY_IPHONE
					gameThrivePlatform = new GameThriveIOS(gameObjectName, appId, autoRegister);
	            #elif UNITY_WP8
	                gameThrivePlatform = new GameThriveWP(appId);
				#endif
				notificationDelegate = inNotificationDelegate;
				
				#if !UNITY_WP8
					GameObject go = new GameObject(gameObjectName);
					go.AddComponent<GameThrive>();
					DontDestroyOnLoad(go);
				#endif
				
				initialized = true;
			#endif
		#else
			print("Please run GameThrive on a device to see push notifications.");
		#endif
	}
Esempio n. 13
0
 /// <summary>
 /// Fired when a notification was received
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 public async Task OnNotificationAsync(NotificationReceivedEventArgs e)
 {
     if (NotificationReceived != null)
     {
         await NotificationReceived.Invoke(e);
     }
 }
Esempio n. 14
0
            private void RegisterNotification()
            {
                // Storing a delegate in class field is necessary to prevent garbage collector from collecting
                // the delegate before it is called. Otherwise, CallbackOnCollectedDelegate may occur.
                _notificationCallback = new WLAN_NOTIFICATION_CALLBACK((data, context) =>
                {
                    var notificationData = Marshal.PtrToStructure <WLAN_NOTIFICATION_DATA>(data);
                    if (notificationData.NotificationSource != WLAN_NOTIFICATION_SOURCE_ACM)
                    {
                        return;
                    }

                    NotificationReceived?.Invoke(null, notificationData);
                });

                var result = WlanRegisterNotification(
                    Handle,
                    WLAN_NOTIFICATION_SOURCE_ACM,
                    false,
                    _notificationCallback,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    0);

                CheckResult(nameof(WlanRegisterNotification), result, true);
            }
Esempio n. 15
0
        /// <summary>
        /// Receives incoming notifications and informs any subscribers.
        /// </summary>
        private void NotificationProcessingThread()
        {
            while (!_isDisposed)
            {
                Thread.Sleep(1);

                // only bother if it's been fully converted, otherwise it will gobble up the initial status response
                if (NotificationSession == null || !NotificationSession.Options.HasFlag(XboxConnectionOptions.NotificationSession))
                {
                    continue;
                }

                // look for a new notification
                string notification = NotificationSession?.TryReceiveLine();
                if (notification == null)
                {
                    continue;
                }

                // save for later
                Logger?.Debug($"Notification received: {notification}");
                NotificationHistory.Enqueue(notification);

                // start dequeuing old entries if greater than max history count
                if (NotificationHistory.Count > MaxNotificationHistoryCount)
                {
                    string garbage;
                    NotificationHistory.TryDequeue(out garbage);
                }

                // inform any subscribers
                NotificationReceived?.Invoke(this, new XboxNotificationEventArgs(notification));
            }
        }
Esempio n. 16
0
        public static void Init(string appId, NotificationReceived inNotificationDelegate = null)
        {
            if (initDone)
            {
                return;
            }

            mAppId = appId;
            notificationDelegate = inNotificationDelegate;
            mPlayerId            = settings.Contains("GameThrivePlayerId") ? (string)settings["GameThrivePlayerId"] : null;
            mChannelUri          = settings.Contains("GameThriveChannelUri") ? (string)settings["GameThriveChannelUri"] : null;

            string channelName = "GameThriveApp" + appId;

            var pushChannel = HttpNotificationChannel.Find(channelName);

            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                SubscribeToChannelEvents(pushChannel);

                pushChannel.Open();
                pushChannel.BindToShellToast();
                fallBackOneSignalSession = new Timer((o) => Deployment.Current.Dispatcher.BeginInvoke(() => SendSession(null)), null, 20000, Timeout.Infinite);
            }
            else   // Else gets run on the 2nd open of the app and after. This happens on WP8.0 but not WP8.1
            {
                SubscribeToChannelEvents(pushChannel);

                if (!pushChannel.IsShellToastBound)
                {
                    pushChannel.BindToShellToast();
                }

                // Since the channel was found ChannelUriUpdated does not fire so send an on session event.
                SendSession(null);
            }

            lastPingTime = DateTime.Now.Ticks;
            PhoneApplicationService.Current.Closing     += (s, e) => SaveActiveTime();
            PhoneApplicationService.Current.Deactivated += (s, e) => SaveActiveTime();
            PhoneApplicationService.Current.Activated   += AppResumed;

            // Using Disatcher due to Unity threading issues with Application.Current.RootVisual.
            // Works fine with normal native apps too.
            Deployment.Current.Dispatcher.BeginInvoke(() => {
                var startingPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage;

                if (startingPage.NavigationContext.QueryString.ContainsKey("GameThriveParams"))
                {
                    NotificationOpened(null, startingPage.NavigationContext.QueryString["GameThriveParams"]);
                }

                SendPing(GetSavedActiveTime());

                initDone = true;
            });
        }
Esempio n. 17
0
 public void ReceiveNotification(string title, string message)
 {
     NotificationReceived?.Invoke(null, new NotificationEventArgs()
     {
         Title   = title,
         Message = message
     });
 }
Esempio n. 18
0
 private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     if (sender == notificationCharacteristic)
     {
         Debug.WriteLine($"Received notification of data to Bluetooth LE characteristic.");
         NotificationReceived?.Invoke(this, new NotifyEventArgs(args.CharacteristicValue.ToArray()));
     }
 }
Esempio n. 19
0
            public void Activate(string appUserModelId, string invokedArgs, NOTIFICATION_USER_INPUT_DATA[] data,
                                 uint dataCount)
            {
                var keyValuePairs = Enumerable.Range(0, (int)dataCount)
                                    .ToDictionary(i => data[i].Key, i => data[i].Value);

                NotificationReceived?.Invoke(this, new NotificationReceivedEventArgs(invokedArgs, keyValuePairs));
            }
Esempio n. 20
0
        /// <inheritdoc/>
        public NotificationParsingResult Parse(NotificationReceived notification)
        {
            var content = notification.Message;

            var fragments = content.Replace(" ", string.Empty).Split(Separators).Select(s => new NotificationFragment(s));
            var result    = new NotificationParsingResult(fragments);

            return(result);
        }
Esempio n. 21
0
        private async Task <bool> RaiseNotificationReceivedAsync(Notification envelope)
        {
            var eventArgs = new EnvelopeEventArgs <Notification>(envelope);

            NotificationReceived?.RaiseEvent(this, eventArgs);
            await eventArgs.WaitForDeferralsAsync().ConfigureAwait(false);

            return(true);
        }
 public void ReceiveNotification(string title, string message)
 {
     var args = new NotificationEventArgs()
     {
         Title = title,
         Message = message,
     };
     NotificationReceived?.Invoke(null, args);
 }
Esempio n. 23
0
        public void ReceiveNotification(string resourceName)
        {
            var args = new NotificationEventArgs()
            {
                ResourceName = resourceName,
            };

            NotificationReceived?.Invoke(null, args);
        }
Esempio n. 24
0
        public void ReceiveNotification(NotificationInfo info)
        {
            var args = new NotificationEventArgs()
            {
                Info = info
            };

            NotificationReceived?.Invoke(null, args);
        }
Esempio n. 25
0
 public void ReceiveNotification(string title, string message)
 {
     //var args = new NotificationEventArgs()
     //{
     //    Title = title,
     //    Message = message,
     //};
     NotificationReceived?.Invoke(null, null);
 }
Esempio n. 26
0
        public Task RaiseMessage(NotificationType notificationType, MarkupString message, string title = null, Action <NotificationOptions> options = null)
        {
            var notificationOptions = NotificationOptions.Default;

            options?.Invoke(notificationOptions);

            NotificationReceived?.Invoke(this, new(notificationType, message, title, notificationOptions) );

            return(Task.CompletedTask);
        }
    public Task Error(string message, string title = null, Action <UiNotificationOptions> options = null)
    {
        var uiNotificationOptions = CreateDefaultOptions();

        options?.Invoke(uiNotificationOptions);

        NotificationReceived?.Invoke(this, new UiNotificationEventArgs(UiNotificationType.Error, message, title, uiNotificationOptions));

        return(Task.CompletedTask);
    }
        public static void StartListening()
        {
            var queryString = new Dictionary <string, string>()
            {
                { "token", ApiToken }
            };

            _connection = new HubConnection("https://stormaio.net/", queryString);
            _hubProxy   = _connection.CreateHubProxy("BiipApi");
            _hubProxy.On <Product>("ProductUpdated", product => NotificationReceived?.Invoke(product));
            _connection.Start();
        }
Esempio n. 29
0
        public void ReceiveNotification(string title, string description, string authReqId, ICollection <NotificationPermission> permissions)
        {
            var args = new NotificationEventArgs()
            {
                Title       = title,
                Description = description,
                AuthReqId   = authReqId,
                Permissions = permissions
            };

            NotificationReceived?.Invoke(null, args);
        }
Esempio n. 30
0
 public void ReceiveNotification(string title, string message, bool isValid)
 {
     if (isValid)
     {
         var args = new NotificationEventArgs()
         {
             Title   = title.Substring(21),
             Message = message
         };
         NotificationReceived?.Invoke(null, args);
     }
 }
        public void DelegarAccionDeNotificacion(MensajeSocio mensaje)
        {
            NotificationReceived?.Invoke(this, mensaje);
            var paginaSolicitarServicio = typeof(SolicitarServicio);
            var paginaActual            = App.Current.MainPage.Navigation.NavigationStack[App.Current.MainPage.Navigation.NavigationStack.Count - 1];

            if (paginaActual.GetType() == paginaSolicitarServicio)
            {
                var dtx      = paginaActual.BindingContext as Core.Lib.ViewModels.Socios.SolicitarServicioViewModel;
                var servicio = new SolicitudServicio
                {
                    Mensaje           = mensaje.MensajePrincipal,
                    ClaveTipoServicio = mensaje.ClaveTipoServicio,
                    FechaSolicitud    = mensaje.FechaSolicitud,
                    FolioSolicitud    = mensaje.FolioSolicitud,
                    IdCliente         = mensaje.IdCliente,
                    IdSolicitud       = mensaje.IdSolicitud,
                    IdTipoSolicitud   = mensaje.IdTipoSolicitud,
                    NombreCliente     = mensaje.NombreCliente,
                    NombreServicio    = mensaje.NombreServicio,
                    TipoServicio      = mensaje.TipoServicio,
                    Ubicacion         = mensaje.Ubicacion,
                    TipoNotificacion  = mensaje.TipoNotificacion
                };
                if (mensaje.TipoNotificacion.Equals((int)TipoNotificacionEnum.ClienteSolicita))
                {
                    dtx.MostrarModalSolicitudCommand.Execute(servicio);
                }
                else if (mensaje.TipoNotificacion.Equals((int)TipoNotificacionEnum.Alerta))
                {
                    dtx.AbrirModalAlertaCommand.Execute(mensaje.MensajePrincipal);
                }
            }
            else
            {
                MPS.Core.Lib.Helpers.Settings.Current.Solicitud = new SharedAPIModel.Socios.SolicitudServicio
                {
                    Mensaje           = mensaje.MensajePrincipal,
                    ClaveTipoServicio = mensaje.ClaveTipoServicio,
                    FechaSolicitud    = mensaje.FechaSolicitud,
                    FolioSolicitud    = mensaje.FolioSolicitud,
                    IdCliente         = mensaje.IdCliente,
                    IdSolicitud       = mensaje.IdSolicitud,
                    IdTipoSolicitud   = mensaje.IdTipoSolicitud,
                    NombreCliente     = mensaje.NombreCliente,
                    NombreServicio    = mensaje.NombreServicio,
                    TipoServicio      = mensaje.TipoServicio,
                    Ubicacion         = mensaje.Ubicacion,
                    TipoNotificacion  = mensaje.TipoNotificacion
                };
            }
        }
        public void NotifyError(string message)
        {
            var notification = new Notification
            {
                At               = DateTime.Now,
                Id               = 0,
                Code             = 0,
                Message          = message,
                NotificationType = NotificationType.Error
            };

            NotificationReceived?.Invoke(this, notification);
        }
        public static void Init(string appId, NotificationReceived inNotificationDelegate = null)
        {
            if (initDone)
                return;

            mAppId = appId;
            notificationDelegate = inNotificationDelegate;
            mPlayerId = settings.Contains("GameThrivePlayerId") ? (string)settings["GameThrivePlayerId"] : null;
            mChannelUri = settings.Contains("GameThriveChannelUri") ? (string)settings["GameThriveChannelUri"] : null;

            string channelName = "GameThriveApp" + appId;

            var pushChannel = HttpNotificationChannel.Find(channelName);

            if (pushChannel == null) {
                pushChannel = new HttpNotificationChannel(channelName);

                SubscribeToChannelEvents(pushChannel);

                pushChannel.Open();
                pushChannel.BindToShellToast();
                fallBackGameThriveSession = new Timer((o) => Deployment.Current.Dispatcher.BeginInvoke(() => SendSession(null)), null, 20000, Timeout.Infinite);
            }
            else { // Else gets run on the 2nd open of the app and after. This happens on WP8.0 but not WP8.1
                SubscribeToChannelEvents(pushChannel);

                if (!pushChannel.IsShellToastBound)
                    pushChannel.BindToShellToast();

                // Since the channel was found ChannelUriUpdated does not fire so send an on session event.
                SendSession(null);
            }

            lastPingTime = DateTime.Now.Ticks;
            PhoneApplicationService.Current.Closing += (s, e) => SaveActiveTime();
            PhoneApplicationService.Current.Deactivated += (s, e) => SaveActiveTime();
            PhoneApplicationService.Current.Activated += AppResumed;

            // Using Disatcher due to Unity threading issues with Application.Current.RootVisual.
            // Works fine with normal native apps too.
            Deployment.Current.Dispatcher.BeginInvoke(() => {
                var startingPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage;

                if (startingPage.NavigationContext.QueryString.ContainsKey("GameThriveParams"))
                    NotificationOpened(startingPage.NavigationContext.QueryString["GameThriveParams"]);

                SendPing(GetSavedActiveTime());

                initDone = true;
            });
        }
 public static void Init(string appId, NotificationReceived inNotificationDelegate = null)
 {
 }
Esempio n. 35
0
	// Parameter defaulting split out into different methods so they are compatible with UnityScript (AKA Unity Javascript).
	public static void Init(string appId, string googleProjectNumber, NotificationReceived inNotificationDelegate) {
		Init(appId, googleProjectNumber, inNotificationDelegate, true);
	}