I have a background agent for my windows phone 8.1(C#) which listens to push notifications.
I also have a foreground App and it handles push notification if it is running.
The problem is that the background agent invokes a custom method await SyncPushChanges.initUpdate(true);
several times causing duplicate values in my sqlite database.
Here is code for foreground delegate:
static async void channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
//Init update from the server
await SyncPushChanges.initUpdate();
//Prevent background agentt from being invoked
args.Cancel = true;
}
Code In background Agent
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferal = taskInstance.GetDeferral();//Save on CPU seconds since we are doing async
//Get the token and invoke get new data
await SyncPushChanges.initUpdate(true);
deferal.Complete();
}
Anyone who might know why am having my method invokes many times?Your help will be highly appreciated
I found a solution myself. The issue was that I was not unregistering my background agent and this caused it to work incorrectly when the app was updated(In this case when I run the application again from VS2013). The following code did the magic
BackgroundExecutionManager.RemoveAccess();
//Unregister the Background Agent
var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == "myAgent");
if (entry.Value != null)
{
entry.Value.Unregister(true);
}