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.
Related
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.
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
I'm new to the UWP, and I'm facing right now an issue where I want to continue an operation that the app was doing before getting into suspended or terminated state.
I've read about Extended execution and background task, but as far as I have understood for extended execution you have only 30 seconds before it gets terminated or it could be revoked before getting into it.
for Background task I should make another project for it ( Windows Runtime Component) and I have to add an entry in the Declarations in the appxmanifest. It sounds that Background task is the only possible way to achieve it, but how to move an operation (Action, Func, or task or whatever) to background task if the app get into those states and what should happen after resume?!
Any ideas from experienced people?
Windows 10 universal Windows platform (UWP) app lifecycle
Before Windows 8, apps had a simple lifecycle. Win32 and .NET apps are either running or not running. Now, there are three app model in UWP app Running in foreground,Running in background and suspended state. You could know more detail through this official document.
Extended execution
There are cases where an app may need to keep running, rather than be suspended, while it is minimized. If an app needs to keep running, either the OS can keep it running, or it can request to keep running.
For this scenario, you need use ExtendedExecution to realize. ExtendedExecution support to start a long running operation in order to defer the Suspending state. And there are some document and code sample introducing this feature.
Background Task
For Background Task, it provide functionality when your app is suspended or not running. You can also use background tasks for real-time communication apps like VOIP, mail, and IM. However, it will trigger under specific conditions. For more please refer this.
You have mentioned out-process Background Task in your case and another Background Task(in process) could also be used in UWP app. It is simpler to implement than out-of-process background tasks.
I am designing a Windows 10 Universal application using this https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Printing/cs repository as a guide. I currently have fully functional printing by calling:
await Printmanager.ShowPrintUIAsync();
In my application there is also an activity timer that logs the user out after a certain amount of time inactive. This part is working fine, but I am unable to close the print ui upon logout.
Note: Normally to close a windows async operations, you can do something similar to:
IAsyncOperation<bool> printOperation = Printmanager.ShowPrintUIAsync();
printOperation.Cancel();
This works for other AsyncOperation occurences, but I cannot get it to work for the print UI, as the print UI is not a child process of the app, but is a seperate process itself
Thanks in advance!
Also, it seems there was a solution to kill processes in Windows 8 which is no longer supported in Windows 10 applications (Process.GetProcessByName .... or FindWindow)
Perhaps there is someway to kill a Windows 10 process by name?
You can't do that.
All the Metro-style applications work in the highly sandboxed environment and there is no way to directly start an external application.
Taken from this article
maybe the solution is creating a proxy.
How to Start a external Program from Metro App
This could help you, because you can kill the process indirectly.
I hope this helps.
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.