I've got a problem with background task in WinRT application. I register task with two triggers
var builder = new BackgroundTaskBuilder
{
Name = "MyTask",
TaskEntryPoint = "Task.MyTask"
};
builder.SetTrigger(new TimeTrigger(60, false));
builder.Register();
Then i do almost the same:
builder = new BackgroundTaskBuilder
{
Name = "MyTask",
TaskEntryPoint = "Task.MyTask"
};
builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false));
builder.Register();
and in my background task logic i want to determine, which trigger executed background task. taskInstance.TriggerDetails == null
this is always true, when task starts working.
please, help. Thanks in advance!
Related
We meet a issue when using background task on windows 8.1 windows app.
We found that background task which register by time trigger cannot work after reboot on Windows 8.1 device.
Before reboot device it works well which setting time trigger value is 15 minutes.
Does any guys meet same case or have any solution, thanks in advance.
Register background task codes:
await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = "SampleBackgroundTask";
builder.TaskEntryPoint = "Tasks.SampleBackgroundTask";
builder.SetTrigger(new TimeTrigger(15, false));
BackgroundTaskRegistration task = builder.Register();
return task;
Run method codes:
var deferral = taskInstance.GetDeferral();
IToastText02 toastContent = ToastContentFactory.CreateToastText02();
toastContent.Launch = "SampleLaunch";
toastContent.TextHeading.Text ="Sample Test"
toastContent.TextBodyWrap.Text ="Sample Test Content"
toastContent.Duration = ToastDuration.Long;
toastContent.Audio.Loop = true;
toastContent.Audio.Content = ToastAudioContent.LoopingAlarm;
ToastNotification toast1 = toastContent.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(toast1);
deferral.Complete();
I have the following background task:
namespace Background
{
public sealed class BackgroundTask : IBackgroundTask
{
private BackgroundTaskDeferral _deferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
//_deferral = taskInstance.GetDeferral();
}
in a file called Task.cs (not that the filename matters).
The Background namespace is in my Solution, which contains a Packaging project, which contains an UWP solution which should launch the Backgroundtask:
private async void LaunchBackground()
{
await BackgroundExecutionManager.RequestAccessAsync();
var exampleTaskName = "Background";
foreach (var taskA in BackgroundTaskRegistration.AllTasks)
{
if (taskA.Value.Name == exampleTaskName)
{
await new ApplicationTrigger().RequestAsync();
break;
}
}
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Background.BackgroundTask";
BackgroundTaskRegistration task = builder.Register();
await new ApplicationTrigger().RequestAsync();
}
In the UWP and the Packaging project have the following declared in the manifest:
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="Background.BackgroundTask">
<BackgroundTasks>
<Task Type="systemEvent" />
</BackgroundTasks>
</Extension>
</Extensions>
I could not add a reference to the background project in my packagin project, but did so in my UWP project.
Still, when I try to launch it, I get the following:
At: BackgroundTaskRegistration task = builder.Register(); System.ArgumentException: 'Value does not fall within the expected range.'
builder according to debug is - builder {Windows.ApplicationModel.Background.BackgroundTaskBuilder} Windows.ApplicationModel.Background.BackgroundTaskBuilder
Have I left something out, or why isn't it working?
Edit: After adding a trigger:
builder.SetTrigger(new SystemTrigger(SystemTriggerType.BackgroundWorkCostChange, false));
WhichI actually do not want, I get a new error:
At: await new ApplicationTrigger().RequestAsync(); System.Runtime.InteropServices.COMException: 'Error HRESULT E_FAIL has been returned from a call to a COM component.'
Try the following code , we should check for background task access permissions then Register the background task :
var hasAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (hasAccess == BackgroundAccessStatus.DeniedBySystemPolicy
|| hasAccess == BackgroundAccessStatus.DeniedByUser
|| hasAccess == BackgroundAccessStatus.Unspecified)
{
await new MessageDialog("ACCESS DENIED").ShowAsync();
return;
}
/////////////////////begin registering bg task
var task = new BackgroundTaskBuilder
{
Name = "Background",
TaskEntryPoint = typeof(Background.BackgroundTask).ToString()
};
//Trigger is necessary for registering bg tasks but Conditions are optional
//set a trigger for your bg task to run
//for ex. below Trigger will run when toast Notifications (cleared, user pressed an action button and so on)
ToastNotificationActionTrigger actiontrigger = new ToastNotificationActionTrigger();
task.SetTrigger(actiontrigger);
//Optional Conditions like Internet Connection
//var condition = new SystemCondition(SystemConditionType.InternetAvailable);
//task.AddCondition(condition);//set condition
BackgroundTaskRegistration registration = task.Register();//Register the task
Also we should check if background task is already running before Register it.
Something like below code snippet:
var isAlreadyRegistered = BackgroundTaskRegistration.AllTasks.Any(t => t.Value?.Name == "BackroundTask");
if (isAlreadyRegistered)
{
foreach (var tsk in BackgroundTaskRegistration.AllTasks)
{
if (tsk.Value.Name == "BackroundTask")
{
tsk.Value.Unregister(true);
break;
}
}
}
More information Create and register an out-of-process background task
I am trying to add a BT server to my app, and using the "BluetoothRfcommChat" sample project, ("Scenario3_BgChatServer" to be exact - with background task).
It seems that if I register the background task and terminate the app without unregistering - I cant register again (even after reboot).
How can I kill a UWP background task?
Thanks in advance.
Background task registration persists across reboot. You want that to be the case.
If your app wants to renew the registration, you will need to unregister first. You would do this along the lines of:
foreach (var bgTask in BackgroundTaskRegistration.AllTasks)
{
if (bgTask.Value.Name == "MaintenanceTask")
{
bgTask.Value.Unregister(true);
}
}
var requestTask = BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = "MaintenanceTask";
builder.TaskEntryPoint = "BackgroundTasks.MaintenanceTask";
builder.SetTrigger(new MaintenanceTrigger(360, false));
BackgroundTaskRegistration task = builder.Register();
My background task registers but never fires. I have tried to delete the whole project to erase all tasks, changed the name on the TaskBuilder class, and used different conditions. But nothing seems to work. I sometimes get an error that says it can't show me the error.
Here do I build it:
public async void RegisterBackgroundTask()
{
var taskRegistered = false;
var TaskName = "TimeTriggeredTask";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == TaskName)
{
taskRegistered = true;
break;
}
}
var tommorowMidnight = DateTime.Today.AddDays(1);
var timeTilMidnight = tommorowMidnight - DateTime.Now;
var minutesTilMidnight = (uint)timeTilMidnight.TotalMinutes;
if (!taskRegistered)
{
var task = RegisterBackgroundTask("TaskBuilderClass",
"TimeTriggeredTask",
new TimeTrigger(minutesTilMidnight, false),
new SystemCondition(SystemConditionType.InternetAvailable));
await task;
CheckPremieres();
}
}
Builder method:
public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
{
await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = name;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
builder.AddCondition(condition);
BackgroundTaskRegistration task = builder.Register();
//
// Remove previous completion status from local settings.
//
var settings = ApplicationData.Current.LocalSettings;
settings.Values.Remove(name);
return task;
}
This is the task builder class which I also added to the manifest:
public sealed class TaskBuilderClass : IBackgroundTask
{
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// Query BackgroundWorkCost
// Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
// of work in the background task and return immediately.
//
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
var settings = ApplicationData.Current.LocalSettings;
settings.Values["BackgroundWorkCost"] = cost.ToString();
App.nHandler.CheckPremieres();
}
}
I'm pretty sure the task needs to be in its own Windows Runtime Component; I've always done it like this. The Microsoft sample on GitHub also has the tasks in a separate project.
Try doing that. And don't forget to reference the newly created prject from your application. That's the thing that I most always forget.
Once you do that, I also suggest you first trigger the task from Visual Studio Debug Location toolbar, just to make sure everything is configured correctly. It should appear in the dropdown and should work correctly from here, otherwise it won't work when scheduled either.
I Need To Run Some Functions In Background In My Windows Phone 8.1 App.
I Have Created A Different Project For Background Tasks In My Solutions.
But Application Is Crashing When I Try To Register Following BG Task.
Here is My Code To Register Task`
private async void TasksRegistration()
{
var taskRegistered = false;
var TaskName = "FirstBG";
// Checking If Task Is Already Registered..
foreach (var task in Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
taskRegistered = true;
return;
}
}
var builder = new BackgroundTaskBuilder();
builder.Name = TaskName;
builder.TaskEntryPoint = "BackGroundTask.FirstBG";
builder.SetTrigger(new TimeTrigger(15, true));
await BackgroundExecutionManager.RequestAccessAsync();
BackgroundTaskRegistration Task = builder.Register();
}
Application Crashed On Last Line When I Try Register This Task.
I Have Written XML Code In .Appx Manifest.
I had the exact same problem, it is most likely do to the fact that your Background Task Project is not set as a Windows Runtime Component.
Make sure the Output Type: is set to a Windows Runtime Component