The use of background tasks, it is estimated that the big partners are not unfamiliar, and the old week in a certain article also briefly described. Speaking of background tasks, the old week thought of a problem: someone asked, background tasks must be written independently of a runtime component, can you write to the main project code?
Old weeks to answer you seriously: Yes, in the configuration manifest file, you only need to specify in the extension element executable. exe files for the main project.
< extension category = "Windows.backgroundtasks" = "..." executable Span style= "color: #0000ff;" >= "Xxxx.exe" > < backgroundtasks > ... </ > </ extension >
In fact, executable can be set to $targetnametoken$.exe so that when the app is built, the $targetnametoken$ tag is automatically replaced with the actual name of the. exe file.
However, the old week is very seriously not recommended to write the background task to the main project, a this does not conform to the official document of the general requirements, not easy to manage the code classification, two, this practice will have a serious negative effect, if the background task is activated, the foreground app is not running it doesn't matter if the foreground app is running when background task executes , is likely to cause the foreground application process restarts, to the user's feeling is the flash back.
Well, the above is just for everyone to popularize common sense, suggest that everyone in the work best according to the rules, do not always like to engage in those alternative behavior, alternative does not represent innovation, but is naïve.
Today's topic is: Can I use the code to trigger post-mission tasks in the foreground app? We know that the common background tasks have background audio, timers, system events, network Transmission control and other triggers, there is no way to let us manually trigger background tasks trigger it?
Yes, its name is Applicationtrigger, using it, you can activate the background task at any time in the foreground code, and you can also pass parameters to the background task. When you need to perform background tasks, call the Requestasync method of the Applicationtrigger instance directly, and if there are no surprises (such as mudslides, landslides, earthquakes, etc.), then the background task will execute.
The principle has been explained with everyone, the following still use examples to speak it.
First I define a background task, and you guess what it's used for.
Public Sealed classBgtask:ibackgroundtask { Public Async voidRun (ibackgroundtaskinstance taskinstance) {varD =taskinstance.getdeferral (); //Take out data related to the triggerApplicationtriggerdetails details = taskinstance.triggerdetails asapplicationtriggerdetails; if(Details! =NULL) { //Take out the parameters passed overValueSet PS =details. Arguments; intna = Convert.ToInt32 (ps["a"]); intNB = Convert.ToInt32 (ps["b"]); //Start the Operation intx =na; intres =0; while(x <=nb) {Res+=x; X++; awaitTask.delay ( -);//Delay//Report ProgressReportProgress (Taskinstance, (UINT) x, (UINT) NB); } //Save Calculation Resultsapplicationdata.current.localsettings.values["result"] =Res; } d.complete (); } Private voidReportProgress (ibackgroundtaskinstance instance,UINTCUINTt) {...} }
You must have seen the noble character, this task is to do the addition operation, specify a starting value and a final value, from the starting value to add, always add to the final value, each addition to the operand +1. Each of these operations is delayed by 30 milliseconds, which is designed to make it easier to see progress. This task is not very rigorous, such as it does not detect if the final value is less than the initial value of how to deal with, you know the line, the old weeks do not want to complicate the code, only for demonstration.
Then you must remember to refer to the Rutime component project in the main project that wrote the background task class.
Next, configure the manifest file, open the Package.appxmanifest file, locate the application node, note that it is not the Applications node, no S, and then add the extension point.
<ApplicationId= "APP"...>...<Extensions> <ExtensionCategory= "Windows.backgroundtasks"entrypoint= "Backgroundtasks.bgtask" > <Backgroundtasks> <TaskType= "General"/> </Backgroundtasks> </Extension> </Extensions> </Application>
<task type= "General"/> that the post-task is regular type, general-purpose, that is, popular background tasks, rather than elite backstage.
The manifest file is simply declared, the background task is not automatically registered, and you need to use code to complete the registration.
Const stringTask_name ="Comptask"; PrivateBackgroundtaskregistration Taskreg =NULL; protected Override Async voidonnavigatedto (NavigationEventArgs e) {varres =awaitBackgroundexecutionmanager.requestaccessasync (); if(res = = Backgroundaccessstatus.unspecified | | res = =backgroundaccessstatus.unspecified) {showmessage ("background tasks are disabled. ");return; } Taskreg= BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault (t = t.name = = task_name) asbackgroundtaskregistration; //registering a background task if(Taskreg = =NULL) {Backgroundtaskbuilder bd=NewBackgroundtaskbuilder (); //entry pointBd. Taskentrypoint =typeof(Backgroundtasks.bgtask). FullName; //Task NameBd. Name =Task_name; //setting up triggersApplicationtrigger trigger =NewApplicationtrigger (); Bd. Settrigger (trigger); Taskreg=Bd. Register (); ShowMessage ("Background Task registration succeeded. "); } //Add Event HandlingTaskreg.progress + =taskreg_progress; Taskreg.completed+=taskreg_completed; }
Before registering, you should visit backgroundtaskregistration.alltasks to see if the background task you need is registered, and duplicate registration is meaningless.
The following code triggers a background task through Applicationtrigger.
//remove a trigger from a registered taskApplicationtrigger Trigger = Taskreg.trigger asApplicationtrigger; //Prepare ParametersValueSet p =NewValueSet (); p["a"] =N1; p["b"] =N2; //Triggering background Tasks varres =awaitTrigger. Requestasync (P); Switch(res) { CaseApplicationTriggerResult.Allowed:ShowMessage ("The background task is started. "); Break; CaseApplicationTriggerResult.CurrentlyRunning:ShowMessage ("The background task is already running. "); Break; CaseApplicationTriggerResult.DisabledByPolicy:ShowMessage ("administrators are not allowed to perform background tasks. "); Break; CaseApplicationTriggerResult.UnknownError:ShowMessage ("An error has occurred. "); Break;
}
When calling the Requestasync method, you can pass data to the background task, which is encapsulated in the Valueset class, which is actually a dictionary model, key is a string.
The value of the Applicationtriggerresult enumeration is returned after the method call. A value of allowed indicates that the background task has been successfully triggered, and if currentlyrunning indicates that the background task is still running, "the number you dialed is on a call, please try again later", and if the value is Disabledbypolicy, the background task is disabled.
Everything ready to see the results of the operation:
Renders the calculation result.
This example: Http://files.cnblogs.com/files/tcjiaan/triggerbgtfromapp.zip
Well, hungry, to eat, today's cabbage pork soup is more nice. Some netizens put forward, old week can write a Win10 in the toast Notice and Operation Center of some new knowledge points. No problem, the next bad article began, the old week with the big friends to study the adaptive Generic Toast Bar.
"Win10 app development" triggers background tasks from a previous app