Reputation: 3031
For saving the RAW notification
payload in background , I added a Windows Runtime Component
project for implementing background task execution.
And I set a class called 'BgTask' and implemented IBackgroundTask
and Run
method.
namespace MyBgTask
{
public sealed class BgTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var a = taskInstance.GetDeferral();
string taskName = taskInstance.Task.Name;
Debug.WriteLine("Background " + taskName + " starting...");
// Store the content received from the notification so it can be retrieved from the UI.
//RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
//var pushdata = JsonConvert.DeserializeObject<PushModelData>(notification.Content);
//var pushdata = notification.Content;
var pushdata = "anoop";
if (settings.Values.ContainsKey(taskName))
{
var dataaa = settings.Values[taskName].ToString();
Debug.WriteLine(dataaa);
var lst = JsonConvert.DeserializeObject<List<string>>(dataaa);
lst.Add(pushdata);
var seri = JsonConvert.SerializeObject(lst);
Debug.WriteLine("saving >>> " + seri);
settings.Values[taskName] = seri;
}
else
{
var lst = new List<string>();
lst.Add(pushdata);
var seri = JsonConvert.SerializeObject(lst);
Debug.WriteLine("saving >>> " + pushdata);
settings.Values[taskName] = seri;
}
Debug.WriteLine("Background " + taskName + " completed!");
a.Complete();
}
}
}
In the Packagemanifest I registered Pushnotification EntryPoint as
MyBgTask.BgTask
And in the Main page I registered the task
private async void Button_Click(object sender, RoutedEventArgs e)
{
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
try
{
PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channel.PushNotificationReceived += OnPushNotification;
UnregisterBackgroundTask();
RegisterBackgroundTask();
}
catch (Exception ex)
{
// ... TODO
}
}
}
private void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
}
private void RegisterBackgroundTask()
{
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
taskBuilder.TaskEntryPoint = "MyBgTask.BgTask";
taskBuilder.Name = "BgTask";
PushNotificationTrigger trigger = new PushNotificationTrigger();
taskBuilder.SetTrigger(trigger);
try
{
BackgroundTaskRegistration task = taskBuilder.Register();
task.Progress += task_Progress;
task.Completed += BackgroundTaskCompleted;
Debug.WriteLine("Registration success: ");
}
catch (Exception ex)
{
Debug.WriteLine("Registration error: " + ex.Message);
UnregisterBackgroundTask();
}
}
void task_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Debug.WriteLine("progress");
});
}
private void BackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Background work item triggered by raw notification with payload = " + " has completed!");
});
}
private bool UnregisterBackgroundTask()
{
foreach (var iter in BackgroundTaskRegistration.AllTasks)
{
IBackgroundTaskRegistration task = iter.Value;
if (task.Name == "BgTask")
{
task.Unregister(true);
return true;
}
}
return false;
}
Set entry point in the Packagemanifest.
And pushnotification event
is triggering when I send a raw notification to my main project with lots of codes. But the issue is that when the event is firing, the code blocks inside the Run method is not firing . It automatically exits with the message
The program '[4484] BACKGROUNDTASKHOST.EXE' has exited with code 1 (0x1)
and happens every time. And I created another sample blank windows phone silverlight project and implemented the background task. And I tested with sending the RAW notification , and now it is working fine , code block inside Run method is simply doing well. And note that both projects are in the same solution.
I need clarification on the following 1. Why background task is exits automatically at the moment it enters in to the Run method? 2. Is this because my project is larger or taking high application memory ? 3. How can I identify the exact reason ?
Please help me figure out a solution to work it as expected!
Many thanks
Upvotes: 1
Views: 388
Reputation: 946
I think the Problem isn't your BackgroundTask
you can ignore the exitcode 1.
I think your Problem is:
You are telling the os to create a new trigger which starts a new BackgroundTask
when the os recives an PushNotification
. This BackroundTask
is an more or less complety own application which will be started by the os. One of the view things your app and your BackgroundTask shares is the ApplicationData.Current.LocalSettings
where you are able to exchange data between your app and the BackgroundTask
.
When you are creating/registering the Trigger you get an BackgroundTaskRegistration
object which you can use to bind your current running app for example to the completed event.
As long as your app is running everything will work fine, but if your app becomes suspended or closed, your app might lose the binding of the completed event.
If you want to be able to show a Notification to the User while the app isn't running do it in the BackgroundTask
.
If you need to get data from the BackgroundTask i.e. update you local data. Save it to ApplicationData.Current.LocalSettings
and check it an the event binding every time your app gets startet or resumed.
Please keep in mind to make the BackgroundTask
simple because you only have a few seconds computation time per hour per BackgroundTask.
Upvotes: 1