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); }
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); } }
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()); }
/// <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); }
public override Result DoWork() { try { Notifier notifier = new Notifier { Context = _context, NotificationIntent = new Intent(_context, typeof(CheckPasswordActivity)) .SetFlags(ActivityFlags.NewTask) .SetFlags(ActivityFlags.SingleTop) }; notifier.SendNotification("PwdCrypter", _context.Resources.GetString(Resource.String.msgCheckPassword), "{\"action\": \"checkpassword\"}"); Log.Info(Tag, "Local notification sent with success"); // Restituisce la data prevista per la prossima esecuzione long interval = InputData.GetLong("interval", 0); DateTime nextRun = DateTime.MinValue; if (interval > 0) { nextRun = DateTime.Now.AddMinutes(interval); } Data data = new Data.Builder() .PutString("NextDate", nextRun.ToString("dd-MM-yyyy, HH:mm:ss")) .Build(); return(Result.InvokeSuccess(data)); } catch (Exception e) { Log.Error(Tag, "Operation failed. Error: {0}", e.Message); return(Result.InvokeFailure()); } }
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); }
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); }
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); } }
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 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); }
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()); }
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 ); } }
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); } }
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 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); }
private void UpdateProgress(Data.Builder progressDataBuilder, double progress, bool visible) { progressDataBuilder.PutInt(ProgressPercentTag, (int)progress); progressDataBuilder.PutBoolean(ProgressVisibleTag, visible); SetProgressAsync(progressDataBuilder.Build()); }
public Task Register(string taskName, string taskEntryPoint, DateTime startDateTime, TimeKind tKind, uint interval) { if (IsRegistered(taskName)) { return(Task.CompletedTask); } try { DateTime nowNoSecond = DateTime.ParseExact(DateTime.Now.ToString("dd-MM-yyyy HH:mm:00"), "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); uint initialDelay = (uint)Math.Round((startDateTime - nowNoSecond).TotalMinutes, 0); uint timeInterval = interval; Java.Util.Concurrent.TimeUnit unit = Java.Util.Concurrent.TimeUnit.Minutes; switch (tKind) { case TimeKind.Minute: unit = Java.Util.Concurrent.TimeUnit.Minutes; break; case TimeKind.Hour: unit = Java.Util.Concurrent.TimeUnit.Hours; break; case TimeKind.Day: unit = Java.Util.Concurrent.TimeUnit.Days; break; case TimeKind.Month: unit = Java.Util.Concurrent.TimeUnit.Days; timeInterval *= 30; break; case TimeKind.Year: unit = Java.Util.Concurrent.TimeUnit.Days; timeInterval *= 365; break; default: throw new Exception(string.Format("Categoria di tempo {0} non prevista", tKind)); } PeriodicWorkRequest.Builder workRequestedBuilder; if (taskName.CompareTo(App.CheckPasswordBackgroundTaskName) == 0) { workRequestedBuilder = PeriodicWorkRequest.Builder.From <CheckPasswordWorker>(timeInterval, unit); } else if (taskName.CompareTo(App.BackupBackgroundTaskName) == 0) { workRequestedBuilder = PeriodicWorkRequest.Builder.From <BackupWorker>(timeInterval, unit); } else { throw new Exception("Task not found"); } Data data = new Data.Builder() .PutLong("interval", unit.ToMinutes(timeInterval)) .Build(); PeriodicWorkRequest workRequested = (PeriodicWorkRequest)workRequestedBuilder .AddTag(taskName) .SetInitialDelay(initialDelay, Java.Util.Concurrent.TimeUnit.Minutes) .SetInputData(data) .Build(); AppWorkManager.EnqueueUniquePeriodicWork(taskName, ExistingPeriodicWorkPolicy.Replace, workRequested); } catch (Exception e) { Log.Error(Tag, string.Format("Error occurred during scheduling the work with name \"{0}\": {1}", taskName, e.Message)); } return(Task.CompletedTask); }
protected override async Task <Data> DoWorkAsync(CancellationToken cancellationToken) { var notificationId = (GetStateKind() + "+" + _agentAddress).GetHashCode(); Log.Debug("Spawned notification with Id {Id}", notificationId); try { var scheduled = await SystemStateManager.GetScheduledTimeAsync(_agentAddress, GetStateKind()); if (scheduled == null || DateTime.Now > scheduled.Value) { Log.Info("A system state event passed while the device was not working."); return(Data.Empty); } var progressDataBuilder = new Data.Builder(); UpdateProgress(progressDataBuilder, 0, false); if (!HostEndpointAddress.TryParse(_agentAddress, out var address)) { Log.Warn("Address {Address} could not be parsed - aborting process", _agentAddress); return(Data.Empty); } using (var agent = GrpcApplicationAgentFactory.Create(GrpcChannelHub.GetChannelFor(address))) { var hostName = await agent.DesktopClient.GetHostNameAsync(TimeSpan.FromSeconds(5)); var notification = NotificationHelper.DisplayNotification(notificationId, builder => { builder.SetCategory(NotificationCompat.CategoryProgress); builder.SetContentTitle(GetNotificationTitle(hostName)); builder.SetOnlyAlertOnce(true); builder.SetSmallIcon(GetNotificationIcon()); var intent = new Intent(); intent.SetAction(GetAbortAction()); intent.PutExtra(AbortBroadcastReceiver.NotificationIdTag, notificationId); intent.PutExtra(AbortBroadcastReceiver.WorkIdTag, Id.ToString()); intent.PutExtra(AbortBroadcastReceiver.HostAddressTag, _agentAddress); var pendingIntent = PendingIntent.GetBroadcast(Application.Context, notificationId, intent, PendingIntentFlags.OneShot); builder.AddAction(Android.Resource.Drawable.ButtonPlus, "Abort", pendingIntent); }, GetNotificationChannel()); SetForegroundAsync(new ForegroundInfo(notificationId, notification.Build())); var startDifference = scheduled.Value - DateTime.Now; while (scheduled > DateTime.Now) { var currentDifference = scheduled.Value - DateTime.Now; var progress = (100f / startDifference.TotalSeconds) * currentDifference.TotalSeconds; notification.SetProgress(100, (int)progress, false); UpdateProgress(progressDataBuilder, progress, true); notification.SetContentText(currentDifference.ToString("hh\\:mm\\:ss")); NotificationHelper.UpdateNotification(ApplicationContext, notificationId, notification); await Task.Delay(1000, cancellationToken); } UpdateProgress(progressDataBuilder, 0, false); NotificationHelper.DestroyNotification(notificationId); SystemStateManager.Clear(_agentAddress, GetStateKind()); var result = await ExecuteFinalizerAsync(agent); Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(() => { if (result) { ToastHelper.Display(GetSuccessToastMessage(hostName), ToastLength.Long); } else { ToastHelper.Display("Error", ToastLength.Short); } }); } } catch (RpcException e) { Log.Debug(e, "Cancelling work because of an RPC exception"); WorkManager.GetInstance(ApplicationContext).CancelWorkById(Id); } return(Data.Empty); }