background task in windows phone 8.1 - c#

I am using a 3rd party rest api to query data and display it in my app. I have to perform a task like at night 12 approx. it will perform a background task to query data from rest api and update live tile and generate notification. I would like to use only C# only for this task. I don't know what will be best approach to do this task. But I using below code to perform background task to do this which is not working. Not sure why?
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = taskName;
SystemTrigger trigger = new SystemTrigger(SystemTriggerType.InternetAvailable, false);
taskBuilder.SetTrigger(trigger);
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
taskBuilder.TaskEntryPoint = typeof(BackgroundTask.BackgroundTask).FullName;
taskBuilder.Register();
and from background task I am querying data and generating toast notification.
Any help why this code is not working or when this task will fire. Is there any better approach to do above task?
Thanks

Regarding the code you have not working...
For Windows Phone 8.1 unlike Windows 8\8.1, you are required to call BackgroundExecutionManager.RequestAccessAsync() (search MSDN\internet) for ANY background task before registering task(s) whereas in Windows this is only required for some tasks. Make sure your code calls this and validate the returned value before registering your background task(s).
Regarding knowing if your task "worked"...
It's a good idea to have the background task implementation run (IBackgroundTask::Run()) independent of the trigger\conditions you've set to ensure it performs without issue by debugging it. See instructions in the following link: http://msdn.microsoft.com/en-US/library/windows/apps/xaml/jj542416.aspx.
Regarding your use of SystemConditionType.InternetAvailable...
I'm not 100% about this but I'm pretty certain this will be redundant given you already have a SystemTriggerType.InternetAvailable. I don't know of a situation where the trigger would fire but the condition wouldn't be true.
Regarding the requirement you've mentioned...
If I understand your requirement correctly you have different options here:
If your app is a Windows Phone XAML app that need to run based on time, I would recommend either TimeTrigger or MaintenanceTrigger triggers (as opposed to the SystemTrigger). These are both Background Tasks. For general info on Background Tasks and links to the TimeTrigger and MaintenanceTrigger documentation see this MSDN link: http://msdn.microsoft.com/en-US/library/windows/apps/xaml/hh977056.aspx.
If your app is a Windows Phone Silverlight 8.0 app you can use Background Agents, specifically either PeriodicTask or ResourceIntensiveTask. See the links posted by others or search the MSDN\internet for more info.
If your app is a Windows Phone Silverlight 8.1 app you can use the option in either 1 or 2 above.

I think you should try using PeriodicTask. Also consider the constraints mentioned in the link.

create one class with output Type :Windows Runtime Component
and put your Class that inheritance from IBackroundTask so this work
if you use from emulator for launching app, i think your app for register task not active in emulator.

Related

How to perform a simple background task on Xamarin iOS

In our app users can track and submit journeys they have recorded. I need a simple way of creating a task in iOS. I have already created and tested this on Android. It works via:
The user selects the journeys they would like to submit.
Taps sync and a foreground service is created that syncs the journeys to our API.
This service will continue to sync journeys even if the app is put into the background or even closed.
So in short how can i achieve this on iOS 9-13?
I have already tried creating a background-safe tasks using:
nint taskID = UIApplication.SharedApplication.BeginBackgroundTask( () => {});
However, this only gives the task 2 mins to run which isn't enough. I have looked into the NSURlSessions but they require URls, whereas we are using our own API wrapper.
I would simply like a way of creating a task when the user taps 'sync' and this task also being capable to run in the background. I am not too bothered if the task is cancelled when the app is closed, although if possible would like the task to continue.
Thanks.
This service will continue to sync journeys even if the app is put
into the background or even closed.
First, if your app is closed in iOS, I'm sure do can't run any service in background.
Then if your app is put into background, Apple has strict limit to allow apps running in the background. background-tasks has time limits, you can read the document about more information. There is a section about handling-background-task-time-limits which you can have a try.
Also, Apple allows some specific apps to run in background which have to perform tasks in the background. For example, app that needs to play music in background, update location in background and etc. You can see the Application Registration Categories here. If your app meets the requirement there, you can apply for a background running permission from system.
Refer: Backgrounding in Xamarin.iOS
I would advise you to leverage on Shiny to achieve it.
PerformFetch is the closest thing to what you ask for, it will run in the background and update your app when iOS thinks it is needed (it predicts that according to the previous behavior the user will soon open your app and that the new content is available).
The only alternative is to send the push notification when you want the app to be updated.
That's about it, I understand your wish but it is just that - a wish and not something that can be real.

UWP Start background task at startup

I just started learning UWP and i'm really confused on how it works. I already saw tens of posts that talk about my problem but can't figure out how to do what I want.
So I want to make an app that runs on windows startup, I want the app to be not visible so it needs a background Task, how can I trigger this background task without getting to the app UI ?
The app is supposed to have the Background Task always running, and its interface is supposed to be used as "settings" so I don't need the app to be shown on startup.
Thanks.
I found my way here after a lot of googling. to be honest I have come to the same conclusion as Motaz. But as of writing this I am way too invested in what I have already. While what I have here is not the perfect answer to his question. I wanted to come back and post what I've learned for anyone else who ends up here.
My need is a app that when started will monitor a third party USB device until the app is closed (regardless of whether the app is minimized or not)
Windows Template Studio is good, but the docs not so much. Especially when it comes to Background tasks.
I started here: https://github.com/Microsoft/Windows-universal-samples. But there is two problems.
They combined all the examples and some of the code is shared, which makes it difficult to pull a project out and hack it apart without breaking the original examples.
Following their background task example I perpetually had issue with the manifest and and it wanting an audio task
I went back to the template studio and created the simplest version with a background task possible. After a lot of trial and error I got something that works. I have posted it here: https://github.com/PillarOfSociety/WindowsTemplateStudio-BackgroundTask
Some things to note:
I am no expert on UWP and while this runs I have no intent on putting it in the store nor did I try.
If you do download my project and run it, you should be able to just hit the "Add events" and the "Start Back" button and the task should run and update the Progress bar.
I used an ApplicationTrigger. the original example from the template uses a TimeTrigger which takes time in MINUTES (took me too long to figure that out). Supposedly Application triggers have a 30sec timeout.. but on my laptop they live for much longer.. I don't know how long. This page is useful: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/support-your-app-with-background-tasks
The template studio generated BackgroundTaskService will leave background tasks registered after the app is closed, but will NOT make the connection back to them once its rerun, so on a rerun either the task appears not to run, or will crash the app when triggered.
Important Code I discovered:
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
TestText += task.Value.Name; //gets the typename of the task
//task.Value.Unregister(true); //will unregister tasks
}
await Task.CompletedTask;
The tasks in BackgroundTaskRegistration.AllTasks are not the BackgroundTask class that the template studio uses. IN my example I unregister all of them each time it runs so that you have a reference to the task as an instance of BackgroundTask.
Hopefully this helps someone and Good luck!
If you're just starting out use Windows Template Studio, it will be perfect for you. It is an extension of Visual Studio which lets you create new uwp projects with a lot of built in features, and you can only choose the features you want. It will save you a lot of time on basic stuff.
https://github.com/Microsoft/WindowsTemplateStudio

How to Disable UWP App Suspension?

I am using C# to develop a UWP app for Windows 10 running only on desktop computers, targeting platform version 10.0.14393.0. Due to business requirements, the app lifecycle must behave like a traditional Win32 application.
Therefore, I followed the recommendation from this article to request an ExtendedExecutionSession with ExtendedExecutionReason.Unspecified. I also configured Windows to never sleep and never hibernate.
Still, on rare occasions, Windows will revoke the extended execution session with reason SystemPolicy and then proceed to suspend the UWP app.
Two questions:
How can I get more information (system logs? event logs?) regarding what led to Windows revoking the extended execution session?
How can I get rid of these rare cases of suspensions so that the UWP app lifecycle behaves exactly like Win32 applications (that is, stay running until user explicitly stops it from running)?
Thanks!
ExtendedExecutionSession with ExtendedExecutionReason.Unspecified is a subject to multiple restrictions regarding resource consumption. Since your test device doesn't have a battery, then the most likely reason for your app getting suspended is its high memory use. You can try to optimize the app in terms of memory consumption and make use of Memory Management APIs as documentation suggests, but still this doesn't guarantee that your app will never get suspended.
If your app is aimed at business sector then you might consider using more powerful ExtendedExecutionForegroundSession instead of ExtendedExecutionSession. This would probably be the perfect solution for your problem. But it's a restricted capability, which means an app that utilizes it is not allowed to Windows Store - only to Windows Store for Business. You'd also need to manually declare the extendedExecutionUnconstrained capability in the manifest (see the Special and restricted capabilities section of documentation) to take advantage of the API.
Alternatively you can use hacks that prevent app from getting suspended for long periods of time:
Use of App services for communicating with Win32 apps as pnp0a03 suggested.
Use Background Media Playback for playing silent audio sample in the background infinitely in a loop (even if the user stops it manually or another app pauses it to play its own background audio, your app can trace it and automatically restart the playback).
I was trying to solve this for days and days but then found this link. Very good explanation and solution to this and most importantly.. easy to understand.
You need to put the code in the app.xaml.cs and also edit the package manifest file.
You will also need the following directives in the app.xaml.cs
using Windows.ApplicationModel.ExtendedExecution.Foreground;
using System.Threading.Tasks;
non-suspending-uwp
I remembered that previous SO post - His question was : When I use the App service to communicate with Win32 apps, it prevents the app entering suspend state.
I've succeeded to recreate the issue with the sample app that referred at the post.
I don't now that is an intended behavior or not, but it may help to resolve your situation.
UWP application not going to suspend state
According to this article in MSDN magazine you can also use background tasks to keep the application alive. The article claims that background tasks should be preferred over the Extended Session method.
A BackgroundTask Implementation
public sealed class TimerTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
taskInstance.Canceled += TaskInstance_Canceled;
await ShowToastAsync("Hello from Background Task");
deferral.Complete();
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender,
BackgroundTaskCancellationReason reason)
{
// Handle cancellation
deferral.Complete();
}
}
In the application manifest, the background task must also be registered. This registration tells Windows the trigger type, the entry point and the executable host of the task, as follows:
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTasks.TimerTask">
<BackgroundTasks>
<Task Type="timer" />
</BackgroundTasks>
</Extension>
Background Task Registration
private void RegisterBackgroundTasks()
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = "Background Test Class";
builder.TaskEntryPoint = "BackgroundTaskLibrary.TestClass";
IBackgroundTrigger trigger = new TimeTrigger(30, true);
builder.SetTrigger(trigger);
IBackgroundCondition condition =
new SystemCondition(SystemConditionType.InternetAvailable);
builder.AddCondition(condition);
IBackgroundTaskRegistration task = builder.Register();
task.Progress += new BackgroundTaskProgressEventHandler(task_Progress);
task.Completed += new BackgroundTaskCompletedEventHandler(task_Completed);
}
Use Visual Studio debug mode to run the app, and the app will never run into a suspended state. It is kept awakened by Visual Studio.
Ahh, this is just a joke.
I think unfortunately what you expect is a behavior that is in contradiction to the design principles of UWP.
The system reserves the right to suspend a background app after some “deferal”. If you request an extended execution session, you have to prepare for the revocation as well, being connected to wall power does not keep the app running forever.
Option 1 is resort to desktop app, though this may not be an option. If you get this requirement because users like UWP but doesn’t like the idea of “suspended” (What the... suspended??), I am afraid you cannot fulfill this requirement.
Option 2 is... is there any real task that has to be kept running even the app is switched to the background? If the task needs to run periodically, like checking inbox of a mail account, you can use some kind of timer triggered background task.
Option 3: Think about kiosk mode, there is only one app allowed to run on the device, so it cannot be possibly switched to the background and put into suspension.

How to create a Thread in windows phone 8.1

Hi, I've tried to create a Thread in windows phone 8.1 without success.
Althought in msdn documentation is written that Thread is supported, actually do not works (https://msdn.microsoft.com/en-us/library/274eh01d(v=vs.110).aspx)
so I can't figureout how can I create a Thread, I want to create a Syncronization context to execute async on a single thread (not current thread), but just to achieve what event loop do
thanks
update for further information:
I would be more specific:
platform is universal app, so I mean windows 8.1 & windows phone 8.1, no silverlight ecc.
I need to create a thread because I want to create a syncronization context to execute some async code, here is an example about what I mean http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx
the difference from this link is I would use a specific thread for all async code instead current thread.
thanks again
If you just want to run some code asynchronously, look into using Task.Run. It provides a much simpler mechanism than managing threads yourself.
If you are building an Universal Windows Phone 8.1 app, you can't use the .NET Thread type. If you need more control over the execution, you can use the WinRT ThreadPool.
Finally, if you really really need lots of control, there's always CreateThread if you want to write native code (this has recently been added to the allowed list of APIs for Store Apps, although MSDN isn't updated yet).

How can I update my tiles in the background in Windows 8?

How can I update my tiles in the background while my app is not running in the foreground? I tried looking into push notifications, but I don't think that'll get me anywhere.
Where to begin? I know how to create tiles already.
An app cannot update it's tile without running at least once. Because apps do not run immediately on installation, it isn't possible for a tile to be "live" until it is launched. After app installation, the user needs to launch the app for it to set up and begin receiving updates in any form (whether they are push notifications, periodic updates, scheduled notifications, or local notifications raised with or without a background task). The default tile will be shown from the point the user installs the app until the time the app sets up tile updates.
MSDN has a good article on choosing the right notification delivery mechanism, which also links to related code samples:
http://msdn.microsoft.com/en-us/library/windows/apps/hh779721.aspx
As far as I know, you have to use a background task. If the user hasn't run the app once, you can't show any interactive tile data.
You have to use a TileNotification from the Windows.UI.Notifications namespace. The documentation for the namespace is here.
There's also an example Stocks app that uses notifications here (search for 'Tiles and notifications')
Further, there's an 'App tiles and badges' sample that shows both text and image updates to a live tile.
Adding Live tiles to the desktop using c# code:
List<Uri> StoryUrls = new List<Uri>();
StoryUrls .Add(new Uri("tiles.xml"));
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
TileUpdateManager.CreateTileUpdaterForApplication().Clear();
TileUpdateManager.CreateTileUpdaterForApplication().StartPeriodicUpdateBatch(StoryUrls, PeriodicUpdateRecurrence.HalfHour);
The xml should be in the following format:
tiles.xml should follow microsoft format show in step 5 Here
Hope this helps

Categories

Resources