private void ShowLater(NotificationRequest notificationRequest)
        {
            if (notificationRequest.NotifyTime.HasValue == false)
            {
                return;
            }

            Cancel(notificationRequest.NotificationId);

            var triggerTime = NotifyTimeInMilliseconds(notificationRequest.NotifyTime.Value);

            notificationRequest.NotifyTime = null;
            triggerTime -= NotifyTimeInMilliseconds(DateTime.Now);

            var serializedNotification = ObjectSerializer <NotificationRequest> .SerializeObject(notificationRequest);

            var dataBuilder = new Data.Builder();

            dataBuilder.PutString(NotificationCenter.ExtraReturnNotification, serializedNotification);

            var reqbuilder = OneTimeWorkRequest.Builder.From <ScheduledNotificationWorker>();

            reqbuilder.AddTag(notificationRequest.NotificationId.ToString());
            reqbuilder.SetInputData(dataBuilder.Build());
            reqbuilder.SetInitialDelay(triggerTime, TimeUnit.Milliseconds);

            var workRequest = reqbuilder.Build();

            WorkManager.Instance.Enqueue(workRequest);
        }
Ejemplo n.º 2
0
        private void ShowLater(NotificationRequest notificationRequest)
        {
            if (notificationRequest.NotifyTime.HasValue == false ||
                notificationRequest.NotifyTime.Value <= DateTime.Now) // To be consistent with iOS, Do not Schedule notification if NotifyTime is earlier than DateTime.Now
            {
                return;
            }

            Cancel(notificationRequest.NotificationId);

            var notifyTime             = notificationRequest.NotifyTime.Value;
            var serializer             = new ObjectSerializer <NotificationRequest>();
            var serializedNotification = serializer.SerializeObject(notificationRequest);

            using (var dataBuilder = new Data.Builder())
            {
                dataBuilder.PutString(NotificationCenter.ExtraReturnNotification, serializedNotification);

                var requestBuilder = OneTimeWorkRequest.Builder.From <ScheduledNotificationWorker>();
                requestBuilder.AddTag(notificationRequest.NotificationId.ToString(CultureInfo.CurrentCulture));
                requestBuilder.SetInputData(dataBuilder.Build());
                var diff = (long)(notifyTime - DateTime.Now).TotalMilliseconds;
                requestBuilder.SetInitialDelay(diff, TimeUnit.Milliseconds);

                var workRequest = requestBuilder.Build();
                WorkManager.Instance.Enqueue(workRequest);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="notificationRequest"></param>
        protected internal virtual void EnqueueWorker(NotificationRequest notificationRequest)
        {
            if (!notificationRequest.NotifyTime.HasValue)
            {
                Log($"{nameof(notificationRequest.NotifyTime)} value doesn't set!");
                return;
            }

            var notifyTime             = notificationRequest.NotifyTime.Value;
            var serializedNotification = ObjectSerializer.SerializeObject(notificationRequest);

            // Why serialized options separately ?
            // System.Xml.Serialization.XmlSerializer Deserialize and Serialize methods ignore
            // object property "Android" when linking option set to "SDK Assemblies Only"
            var serializedNotificationAndroid = ObjectSerializer.SerializeObject(notificationRequest.Android);

            Log($"NotificationServiceImpl.ShowLater: SerializedNotification [{serializedNotification}]");

            using var dataBuilder = new Data.Builder()
                                    .PutString(NotificationCenter.ExtraReturnNotification, serializedNotification)
                                    .PutString($"{NotificationCenter.ExtraReturnNotification}_Android", serializedNotificationAndroid);
            var data = dataBuilder.Build();
            var tag  = notificationRequest.NotificationId.ToString(CultureInfo.CurrentCulture);
            var diff = (long)(notifyTime - DateTime.Now).TotalMilliseconds;

            var workRequest = OneTimeWorkRequest.Builder.From <ScheduledNotificationWorker>()
                              .AddTag(tag)
                              .SetInputData(data)
                              .SetInitialDelay(diff, TimeUnit.Milliseconds)
                              .Build();

            WorkManager?.Enqueue(workRequest);
        }
Ejemplo n.º 4
0
        public static OneTimeWorkRequest CreateOneTime <TWorker>(Action <OneTimeWorkRequest.Builder> workRequestMutator = null, Action <Constraints.Builder> constraintsMutator = null, Action <Data.Builder> inputData = null)
        {
            var requestBuilder = new OneTimeWorkRequest.Builder(typeof(TWorker));

            if (inputData != default)
            {
                var dataBuilder = new Data.Builder();
                inputData.Invoke(dataBuilder);
                requestBuilder.SetInputData(dataBuilder.Build());
            }

            workRequestMutator?.Invoke(requestBuilder);

            if (constraintsMutator == null)
            {
                requestBuilder.SetConstraints(Constraints.None);
            }
            else
            {
                var constraintsBuilder = new Constraints.Builder();
                constraintsMutator?.Invoke(constraintsBuilder);
                requestBuilder.SetConstraints(constraintsBuilder.Build());
            }

            return(requestBuilder.Build());
        }
Ejemplo n.º 5
0
        private void ShowLater(NotificationRequest notificationRequest)
        {
            if (notificationRequest.NotifyTime is null ||
                notificationRequest.NotifyTime.Value <= DateTime.Now) // To be consistent with iOS, Do not Schedule notification if NotifyTime is earlier than DateTime.Now
            {
                return;
            }

            Cancel(notificationRequest.NotificationId);

            var notifyTime             = notificationRequest.NotifyTime.Value;
            var serializedNotification = ObjectSerializer.SerializeObject(notificationRequest);
            // Why serialized options separately ?
            // System.Xml.Serialization.XmlSerializer Deserialize and Serialize methods ignore object property "Android" when linking option set to "SDK Assemblies Only"
            var serializedNotificationAndroid = ObjectSerializer.SerializeObject(notificationRequest.Android);

            Log.Info(Application.Context.PackageName, $"NotificationServiceImpl.ShowLater: SerializedNotification [{serializedNotification}]");
            using var dataBuilder = new Data.Builder();
            dataBuilder.PutString(NotificationCenter.ExtraReturnNotification, serializedNotification);
            dataBuilder.PutString($"{NotificationCenter.ExtraReturnNotification}_Android", serializedNotificationAndroid);

            var requestBuilder = OneTimeWorkRequest.Builder.From <ScheduledNotificationWorker>();

            requestBuilder.AddTag(notificationRequest.NotificationId.ToString(CultureInfo.CurrentCulture));
            requestBuilder.SetInputData(dataBuilder.Build());
            var diff = (long)(notifyTime - DateTime.Now).TotalMilliseconds;

            requestBuilder.SetInitialDelay(diff, TimeUnit.Milliseconds);

            var workRequest = requestBuilder.Build();

            _workManager?.Enqueue(workRequest);
        }
Ejemplo n.º 6
0
        public Object AttachCompleter(CallbackToFutureAdapter.Completer p0)
        {
            Log.Debug(TAG, $"Executing.");

            //Switch to background thread.
            Task.Run(async() =>
            {
                //Perform a process here, simulated by a delay for 5 seconds.

                var delaySeconds      = 5;
                var progress          = 0;
                var progressIncrement = 100 / delaySeconds;
                var dataBuilder       = new Data.Builder();

                for (int i = 0; i < delaySeconds + 1; i++)
                {
                    await Task.Delay(1000);
                    progress += progressIncrement;
                    dataBuilder.PutInt("Progress", progress);
                    SetProgressAsync(dataBuilder.Build());
                }

                Log.Debug(TAG, "Completed.");

                //Set a Success Result on the completer and return it.
                return(p0.Set(Result.InvokeSuccess()));
            });

            return(TAG);
        }
        public override void OnMessageReceived(RemoteMessage message)
        {
            //Log.Debug(TAG, "From: " + message.From);
            //var body = message.GetNotification().Body;
            //Log.Debug(TAG, "Notification Message Body: " + body);
            Log.Info(TAG, $"Received a firebase request from {message.From}.");
            if (message.From == $"/topics/{MainActivity.CHANNEL_ID}")
            {
                Log.Debug(TAG, "Received an announcement.");
                SendNotification(message.GetNotification().Body, message.GetNotification().Title, message.Data);
            }
            else if (message.From == $"/topics/{MainActivity.UPDATE_CHANNEL_NAME}" &&
                     !Preferences.ContainsKey("DisableAutoUpdate"))
            {
                Log.Debug(TAG, "Received an update request.");

                if (!message.Data.ContainsKey("region") || !int.TryParse(message.Data["region"], out var region))
                {
                    Log.Warn(TAG, "Firebase message missing region.");
                    return;
                }

                if (region < 1 || region > 2)
                {
                    Log.Warn(TAG, "Invalid region for update request.");
                    return;
                }

                string preferencesKey = "";
                switch (region)
                {
                case 1:
                    preferencesKey = $"InstalledScript_{FGORegion.Jp}";
                    break;

                case 2:
                    preferencesKey = $"InstalledScript_{FGORegion.Na}";
                    break;
                }

                if (Preferences.Get(preferencesKey, null) == null)
                {
                    Log.Warn(TAG, "User hasn't installed any script for this region.");
                    return;
                }

                var data = new Data.Builder();
                data.PutInt("region", region);
                data.PutString("preferencesKey", preferencesKey);
                var finalData = data.Build();
                var builder   = OneTimeWorkRequest.Builder.From <RayshiftTranslationUpdateWorker>();
                builder.SetInputData(finalData);

                OneTimeWorkRequest request = builder.Build();
                WorkManager.Instance.Enqueue(request);
            }
        }
Ejemplo n.º 8
0
        protected override void RegisterNative(JobInfo jobInfo)
        {
            this.CancelNative(jobInfo);

            //WorkManager.Initialize(this.context.AppContext, new Configuration())
            var constraints = new Constraints.Builder()
                              .SetRequiresBatteryNotLow(jobInfo.BatteryNotLow)
                              .SetRequiresCharging(jobInfo.DeviceCharging)
                              .SetRequiredNetworkType(ToNative(jobInfo.RequiredInternetAccess))
                              .Build();

            var data = new Data.Builder();

            data.PutString(ShinyJobWorker.ShinyJobIdentifier, jobInfo.Identifier);

            if (jobInfo.Repeat)
            {
                var request = new PeriodicWorkRequest.Builder(typeof(ShinyJobWorker), TimeSpan.FromMinutes(15))
                              .SetConstraints(constraints)
                              .SetInputData(data.Build())
                              .Build();

                this.Instance.EnqueueUniquePeriodicWork(
                    jobInfo.Identifier,
                    ExistingPeriodicWorkPolicy.Replace,
                    request
                    );
            }
            else
            {
                var worker = new OneTimeWorkRequest.Builder(typeof(ShinyJobWorker))
                             .SetInputData(data.Build())
                             .SetConstraints(constraints)
                             .Build();

                this.Instance.EnqueueUniqueWork(
                    jobInfo.Identifier,
                    ExistingWorkPolicy.Append,
                    worker
                    );
            }
        }
Ejemplo n.º 9
0
        public override async Task Schedule(JobInfo jobInfo)
        {
            await base.Schedule(jobInfo);

            //WorkManager.Initialize(this.context.AppContext, new Configuration())
            var constraints = new Constraints.Builder()
                              .SetRequiresBatteryNotLow(jobInfo.BatteryNotLow)
                              .SetRequiresCharging(jobInfo.DeviceCharging)
                              .SetRequiredNetworkType(ToNative(jobInfo.RequiredInternetAccess))
                              .Build();

            var data = new Data.Builder();

            foreach (var parameter in jobInfo.Parameters)
            {
                data.Put(parameter.Key, parameter.Value);
            }

            if (jobInfo.Repeat)
            {
                var request = PeriodicWorkRequest
                              .Builder
                              .From <ShinyJobWorker>(TimeSpan.FromMinutes(20))
                              .SetConstraints(constraints)
                              .SetInputData(data.Build())
                              .Build();

                WorkManager.Instance.EnqueueUniquePeriodicWork(
                    jobInfo.Identifier,
                    ExistingPeriodicWorkPolicy.Replace,
                    request
                    );
            }
            else
            {
                var worker = new OneTimeWorkRequest.Builder()
                             .SetInputData(data.Build())
                             .SetConstraints(constraints);
            }
        }
Ejemplo n.º 10
0
        public void SetupDNDWork(DateTime date, string name)
        {
            var data = new Data.Builder();

            data.PutString("Type", "DND");

            var work = OneTimeWorkRequest.Builder.From <NotificationWorkManager>()
                       .SetInitialDelay(date.Subtract(DateTime.Now))
                       .SetInputData(data.Build())
                       .Build();

            WorkManager.GetInstance(AndroidApp.Context).EnqueueUniqueWork(name, ExistingWorkPolicy.Keep, work);
        }
        public override Result DoWork()
        {
            Data taskData       = WorkerParameters.InputData;
            var  taskDataString = taskData.GetString("id");

            var    outputData = new Data.Builder().PutString("id", taskDataString);
            Random random     = new Random();
            int    val        = random.Next(1, 4);

            if (val == 1)
            {
                Debug.WriteLine("Fail");
                return(Result.InvokeFailure(outputData.Build()));
            }
            if (val == 2)
            {
                Debug.WriteLine("Retry");
                return(Result.InvokeRetry());
            }
            Debug.WriteLine("Success");
            return(Result.InvokeSuccess(outputData.Build()));
        }
        public void RegisterPeriodicBackgroundProcess <T>(int repeatMins, BackgroundTaskMetadata metaData) where T : ICoreJob, new()
        {
            repeatMins = repeatMins >= 20 ? repeatMins : 20; //This is the minimum
            var tag  = typeof(T).Name;
            var data = new Data.Builder();

            data.Put("activatorDetails", $"{typeof(T).Assembly.GetName().Name},{typeof(T).FullName}");

            var constraints = new Constraints.Builder();

            if (metaData != null)
            {
                constraints.SetRequiresCharging(metaData.RequiresCharging);
                constraints.SetRequiresBatteryNotLow(metaData.RequiresBatteryNotLow);
                if (metaData.RequiresNetworkType != null)
                {
                    if (metaData.RequiresNetworkType == "Connected")
                    {
                        constraints.SetRequiredNetworkType(NetworkType.Connected);
                    }
                    if (metaData.RequiresNetworkType == "Metered")
                    {
                        constraints.SetRequiredNetworkType(NetworkType.Metered);
                    }
                    if (metaData.RequiresNetworkType == "NotRequired")
                    {
                        constraints.SetRequiredNetworkType(NetworkType.NotRequired);
                    }
                    if (metaData.RequiresNetworkType == "NotRoaming")
                    {
                        constraints.SetRequiredNetworkType(NetworkType.NotRoaming);
                    }
                    if (metaData.RequiresNetworkType == "Unmetered")
                    {
                        constraints.SetRequiredNetworkType(NetworkType.Unmetered);
                    }
                }
                constraints.SetRequiresDeviceIdle(metaData.RequiresDeviceIdle);
                constraints.SetRequiresStorageNotLow(metaData.RequiresStorageNotLow);
            }

            var pwr = PeriodicWorkRequest.Builder.From <BackgroundTaskWorker>(TimeSpan.FromMinutes(repeatMins))
                      .SetConstraints(constraints.Build())
                      .SetInputData(data.Build())
                      .AddTag(tag)
                      .Build();

            WorkManager.Instance.EnqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.Keep, pwr);

            periodic.Add(tag, pwr.Id);
        }
        public void RegisterBackgroundProcess <T>() where T : ICoreJob, new()
        {
            var tag  = typeof(T).Name;
            var data = new Data.Builder();

            data.Put("activatorDetails", $"{typeof(T).Assembly.GetName().Name},{typeof(T).FullName}");

            var otwr = OneTimeWorkRequest.Builder.From <BackgroundTaskWorker>()
                       .SetInputData(data.Build())
                       .AddTag(tag)
                       .Build();

            WorkManager.Instance.EnqueueUniqueWork(tag, ExistingWorkPolicy.Keep, otwr);
        }
Ejemplo n.º 14
0
        public async Task <string> StartUploadForIdAsync(Guid id)
        {
            Data.Builder data = new Data.Builder();
            data.PutString("id", id.ToString());
            OneTimeWorkRequest oneTimeWorkRequest = OneTimeWorkRequest.Builder.From <RandomUploadWorker>()
                                                    .SetInputData(data.Build())
                                                    .Build();

            WorkManager.Instance.Enqueue(oneTimeWorkRequest);

            ILifecycleOwner owner = ProcessLifecycleOwner.Get();

            //Observe what happened to this request so we can notify the UI
            WorkManager.Instance.GetWorkInfoByIdLiveData(oneTimeWorkRequest.Id).Observe(owner, new RandomWorkerObserver());
            return(oneTimeWorkRequest.Id.ToString());
        }
        public bool SetNewFutureWork(int workId)
        {
            var logger = new OurLoggerService();

            logger.LogInformation($"Setting new service worker for ${workId} started");

            var workData = new Data.Builder();

            workData.PutInt("WORK_NO", workId);

            Random random = new Random();

            OneTimeWorkRequest someWork = new OneTimeWorkRequest
                                          .Builder(typeof(FutureWorker))
                                          .SetInputData(workData.Build())
                                          .SetInitialDelay(random.Next(1, 30), timeUnit: TimeUnit.Seconds)
                                          .Build();

            WorkManager.Instance.Enqueue(someWork);

            logger.LogInformation($"Setting new service worker for ${workId} complete");
            return(true);
        }
Ejemplo n.º 16
0
 private void UpdateProgress(Data.Builder progressDataBuilder, double progress, bool visible)
 {
     progressDataBuilder.PutInt(ProgressPercentTag, (int)progress);
     progressDataBuilder.PutBoolean(ProgressVisibleTag, visible);
     SetProgressAsync(progressDataBuilder.Build());
 }