From: It Chase Dream Garden (http://www.zmy123.cn/?p=1172)
One of the features of UWP apps is live tiles, so if your app hasn't set up a live tile yet, come with me to add live tiles to your app!
The UWP live tile can be implemented via a message push, which can be implemented through a background task. The way I use it is done by registering a background task.
Method:
To update a live tile with a background task:
Among them, the API used mainly has the following two.
- Ibackgroundtask
- Backgroundtaskbuilder
First step: Create a background task project:
To enable live tiles for your app, add a new Windows Runtime component project to your solution. This is a standalone assembly that the OS needs to load and run in the background when the user installs your app.
- In Solution Explorer, right-click the solution, point to Add, and then click or tap New Project.
- In the Add New Project dialog box, in the Visual C # > Windows Store section, select the Windows Runtime Components template.
- Name the Backgroundtasks project, and then click or tap OK. Microsoft Visual Studio adds this new project to the solution.
- In the main project, add a reference to the Backgroundtasks project.
Such as:
Step two: Implement background tasks
Implement the Ibackgroundtask interface to create classes to update the app's live tile. Background work will take the Run method.
- In Solution Explorer, rename the automatically generated file Class1.cs to BlogFeedBackgroundTask.cs.
- In BlogFeedBackgroundTask.cs, replace the automatically generated code with the stub code of the Blogfeedbackgroundtask class.
- During the implementation of the Run method, add the code for the Getblogfeed and Updatetile methods.
Here to request an online XML document for example, in our It Chase Dream Park RSS Subscription As an example, the following method, will be implemented, the IT Chase Dream Garden new article display on the live tile! Think it's cool not to open the app and know what I've updated? (OK, although I still want you to open the app to see ...) )
The code inside this runtime component is as follows:
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingWindows.ApplicationModel.Background;usingWindows.Data.Xml.Dom;usingWindows.UI.Notifications;usingWindows.Web.Syndication;namespacebackgroundtasks{ Public Sealed classBlogfeedbackgroundtask:ibackgroundtask {//first, let's take a look at the RSS feeds from the It Dream Garden and return the XML document method. The first two are information about setting up a network request header. (can be ignored) Static stringCustomheadername ="user-agent"; Static stringCustomheadervalue ="mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; trident/6.0)"; //This is the RSS address of it Dream Park: Static stringFeedurl =@"Http://www.zmy123.cn/?feed=rss2";//here gets the value of its node as text Static stringTextelementname ="text"; //Note: Here is the beginning of the background task, and so we write the code, here to break the point of debugging, see if the background task can be done here! Public Async voidRun (ibackgroundtaskinstance taskinstance) {backgroundtaskdeferral Deferral=taskinstance.getdeferral (); varFeed =awaitgetblogfeed (); Updatetile (Feed); Deferral.complete (); } Private Static AsyncTask<syndicationfeed>getblogfeed () {SyndicationFeed feed=NULL; Try {//here are the methods that request the most-line XML address, and get to the XML document. Syndicationclient client =Newsyndicationclient (); Client. Bypasscacheonretrieve=true; Client. setRequestHeader (Customheadername, customheadervalue);//Here we get the XML document feedFeed =awaitClient. Retrievefeedasync (NewUri (Feedurl)); } Catch(Exception ex) {Debug.WriteLine (ex). ToString ()); } returnfeed; }//ways to update tiles Private Static voidupdatetile (SyndicationFeed feed) {//with this approach, we can base the addition of live tiles. varUpdater =tileupdatemanager.createtileupdaterforapplication ();//This is set so that the tile can be dynamicUpdater. Enablenotificationqueue (true ); Updater. Clear (); intItemCount =0;//and then here is the point: Remember to divide 3 steps away: foreach(varIteminchfeed. Items) {//1: Create an XML object, see here you want to display several live tiles, if you want to display squares and rectangles, then set a dynamic tile type. //The following two are rectangular dynamic tile, and square dynamic tile, specific style, you can go to the Microsoft website to check. What I'm using here is the text form of the newline. XmlDocument Tilexml =tileupdatemanager.gettemplatecontent (tiletemplatetype.tilewidetext03); XmlDocument TILEXML2=tileupdatemanager.gettemplatecontent (tiletemplatetype.tilesquaretext04); vartitle =item. Title; stringTitleText = title. Text = =NULL?String.Empty:title. Text;//2. Then assign a value to the XML objectTilexml.getelementsbytagname (Textelementname) [0]. InnerText =TitleText;//3. Then update the tile with the Update methodUpdater. Update (Newtilenotification (Tilexml));//4. Finally, it is important to note that Microsoft specifies that the number of live tiles is less than 5, so make a judgment here. if(itemcount++ >5) Break; } } }}
Step three: Set up the package manifest
Open it and add a new background task declaration. Set the entry point for the task to the class name, including its namespace.
- In Solution Explorer, open package.appxmanifest.
- Click or tap the Declarations tab.
- Under Available claims, select Backgroundtasks, and then click Add. Visual Studio adds "backgroundtasks" to "supported claims."
- Under supported task types, make sure that the timer is selected.
- Under App settings, set the entry point to "Backgroundtasks.blogfeedbackgroundtask".
- Click or tap the Application UI tab.
- Set lock screen notifications to lock screen reminders and tile text.
- In the Badge badge field, set the path to a 24x24 pixel icon. Here also to notice, set the tile do not set the wrong, set up, remember to delete the original, or will error.
Such as:
Fourth step: Register a background task
Here Backgroundtaskbuilder is used to register the task.
Here we go back to the app's homepage:
In the home page of your app, add the Registerbackgroundtask method and make the call in the Onnavigatedto event handler.
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Threading.Tasks;usingWindows.ApplicationModel.Background;usingWindows.Data.Xml.Dom;usingwindows.foundation;usingWindows.Foundation.Collections;usingWindows.UI.Xaml;usingWindows.UI.Xaml.Controls;usingWindows.UI.Xaml.Controls.Primitives;usingWindows.UI.Xaml.Data;usingWindows.UI.Xaml.Input;usingWindows.UI.Xaml.Media;usingWindows.UI.Xaml.Navigation;usingWindows.Web.Syndication;//The Blank Page item template is documented athttp://go.microsoft.com/fwlink/p/?LinkID=234238namespacecontosoapp{/// <summary> ///An empty page that can is used on its own or navigated to within a Frame. /// </summary> Public Sealed Partial classMainpage:page { PublicMainPage () { This. InitializeComponent (); } protected Override voidonnavigatedto (NavigationEventArgs e) {//register the background task in our runtime component here. This. Registerbackgroundtask (); } Private Async voidRegisterbackgroundtask () {//here is some logical processing of the tile update cycle varBackgroundaccessstatus =awaitBackgroundexecutionmanager.requestaccessasync (); if(Backgroundaccessstatus = = Backgroundaccessstatus.allowedmayuseactiverealtimeconnectivity | |Backgroundaccessstatus==backgroundaccessstatus.allowedwithalwaysonrealtimeconnectivity) {foreach(varTaskinchbackgroundtaskregistration.alltasks) {if(Task. Value.name = =taskname) {Task.} Value.unregister (true ); }} backgroundtaskbuilder Taskbuilder=NewBackgroundtaskbuilder (); Taskbuilder.name=TaskName; Taskbuilder.taskentrypoint=Taskentrypoint; Taskbuilder.settrigger (NewTimetrigger ( the,false ) ); varRegistration =Taskbuilder.register (); } } Private Const stringTaskName ="Blogfeedbackgroundtask"; Private Const stringTaskentrypoint ="Backgroundtasks.blogfeedbackgroundtask"; }}
Fifth step: Debug Background tasks
To debug a background task, set a breakpoint in the Run method of the task. In the Debug Location toolbar, select your background task. This causes the system to call the Run method immediately.
- Set a breakpoint in the Run method of the task.
- Press F5 or tap Debug > Start Debugging to deploy and run the app.
- After the app starts, switch back to Visual Studio.
- Make sure the Debug Location toolbar is displayed. The toolbar is located in the View > Toolbars menu.
- On the Debug Location toolbar, click the Pause drop-down menu, and then select Blogfeedbackgroundtask.
- Visual Studio pauses execution at the breakpoint location.
- Press F5 to click "Debug" > "Continue" to continue running the app.
- Press SHIFT+F5 or click "Debug" > "Stop Debugging" to stop debugging.
- Return to the app's tile on the start screen. After a few seconds, tile notifications will appear on your app's tile!
Such as:
Note: It is not possible to deploy directly here, to trigger background tasks by suspending blogfeedbackgroundtask, so if you do not see the live tile, pay attention to the last step above. I was here a long time ago. In this way, we can display live tiles on our It Dream Park app, and it shows what I recently updated, isn't it cool? (So afraid, so you will not open my app ...) )
From: It Chase Dream Garden (http://www.zmy123.cn/?p=1172)
uwp-Live Tile