UWP Dev: Teach you to add live tiles to your app

Source: Internet
Author: User
Tags blank page microsoft website

UWP Dev: Teach you to add live tiles to your app

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.

    1. In Solution Explorer, right-click the solution, point to Add, and then click or tap New Project.
    2. In the Add New Project dialog box, in the Visual C # > Windows Store section, select the Windows Runtime Components template.
    3. Name the Backgroundtasks project, and then click or tap OK. Microsoft Visual Studio adds this new project to the solution.
    4. 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.

    1. In Solution Explorer, rename the automatically generated file Class1.cs to BlogFeedBackgroundTask.cs.
    2. In BlogFeedBackgroundTask.cs, replace the automatically generated code with the stub code of the Blogfeedbackgroundtask class.
    3. 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#
Using system;using system.collections.generic;using system.diagnostics;using system.linq;using System.Text;using System.threading.tasks;using windows.applicationmodel.background;using windows.data.xml.dom;using Windows.ui.notifications;using windows.web.syndication;namespace backgroundtasks{public sealed class Blogfeedbackgroundtask:ibackgroundtask {///First, we'll take a look at the RSS feed for the It chase, and return to the XML document method. The first two are information about setting up a network request header.          (can be ignored) static string customheadername = "User-agent"; static string customheadervalue = "mozilla/5.0 (compatible; MSIE 10.0;          Windows NT 6.2; WOW64; trident/6.0) "; Here is the RSS address of the IT Dream Garden: static string feedurl = @ "Http://www.zmy123.cn/?feed=rss2";//This defines a textelementname, which is used to display the node request to      The data is static string textelementname = "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 void Run (Ibackgroundtaskinstance taskinstance) {backgroundtaskdeferral Deferra        L = taskinstance.getdeferral ();    var feed = await getblogfeed ();            Updatetile (Feed);        Deferral.complete ();            } private static Async task<syndicationfeed> Getblogfeed () {SyndicationFeed feed = null;                try {//Here is the method that requests the most XML address and gets to the XML document.                Syndicationclient client = new Syndicationclient (); Client.                Bypasscacheonretrieve = true; Client. setRequestHeader (Customheadername, customheadervalue);//Here we get the XML document Feed feed = await client.            Retrievefeedasync (New Uri (Feedurl)); } catch (Exception ex) {Debug.WriteLine (ex.            ToString ());        } return feed;            }//How to update tiles private static void Updatetile (SyndicationFeed feed) {//This method allows us to base the addition of live tiles. var updater = tileupdatemanager.createtileupdaterforapplication ();//This is set so that the tile can be dynamic updater.            Enablenotificationqueue (TRUE); Updater.            Clear (); int itemCount = 0;//Then here is the point: Remember to split 3 steps: foreach (var item in feed. 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);  XMLDOCU                ment TILEXML2 = tileupdatemanager.gettemplatecontent (tiletemplatetype.tilesquaretext04); var title = Item.                Title; String titletext = title. Text = = null? String.Empty:title. TEXT;//2. The XML object is then assigned a value of Tilexml.getelementsbytagname (Textelementname) [0]. InnerText = TITLETEXT;//3. Then update the tile updater with the Update method.                Update (New Tilenotification (Tilexml));//4. Finally, it is important to note that Microsoft specifies that the number of live tiles is less than 5, so make a decision 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.

    1. In Solution Explorer, open package.appxmanifest.
    2. Click or tap the Declarations tab.
    3. Under Available claims, select Backgroundtasks, and then click Add. Visual Studio adds "backgroundtasks" to "supported claims."
    4. Under supported task types, make sure that the timer is selected.
    5. Under App settings, set the entry point to "Backgroundtasks.blogfeedbackgroundtask".
    6. Click or tap the Application UI tab.
    7. Set lock screen notifications to lock screen reminders and tile text.
    8. 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#
Using system;using system.collections.generic;using system.io;using system.linq;using System.Threading.Tasks;using Windows.applicationmodel.background;using windows.data.xml.dom;using windows.foundation;using Windows.foundation.collections;using windows.ui.xaml;using windows.ui.xaml.controls;using Windows.ui.xaml.controls.primitives;using windows.ui.xaml.data;using windows.ui.xaml.input;using Windows.ui.xaml.media;using windows.ui.xaml.navigation;using windows.web.syndication;//The Blank Page item template is documented at http://go.microsoft.com/fwlink/p/?  Linkid=234238namespace contosoapp{//<summary>//An empty page so can be used on their own or navigated to    Within a Frame. </summary> public sealed partial class Mainpage:page {public MainPage () {This .        InitializeComponent ();            } protected override void Onnavigatedto (NavigationEventArgs e) {//Register the background task in our runtime component here. This. RegisterbackgroundtasK (); } private async void Registerbackgroundtask () {//Here is some logical processing of the tile update cycle var backgroundaccessstatus = a            Wait Backgroundexecutionmanager.requestaccessasync ();                if (backgroundaccessstatus = = Backgroundaccessstatus.allowedmayuseactiverealtimeconnectivity | | Backgroundaccessstatus = = backgroundaccessstatus.allowedwithalwaysonrealtimeconnectivity) {for Each (var task in backgroundtaskregistration.alltasks) {if (task. Value.name = = taskname) {task.                    Value.unregister (TRUE);                }} Backgroundtaskbuilder Taskbuilder = new Backgroundtaskbuilder ();                Taskbuilder.name = TaskName;                Taskbuilder.taskentrypoint = Taskentrypoint;                Taskbuilder.settrigger (new Timetrigger (false));            var registration = Taskbuilder.register ();    }    } Private Const string taskname = "Blogfeedbackgroundtask";    Private Const string taskentrypoint = "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.

    1. Set a breakpoint in the Run method of the task.
    2. Press F5 or tap Debug > Start Debugging to deploy and run the app.
    3. After the app starts, switch back to Visual Studio.
    4. Make sure the Debug Location toolbar is displayed. The toolbar is located in the View > Toolbars menu.
    5. On the Debug Location toolbar, click the Pause drop-down menu, and then select Blogfeedbackgroundtask.
    6. Visual Studio pauses execution at the breakpoint location.
    7. Press F5 to click "Debug" > "Continue" to continue running the app.
    8. Press SHIFT+F5 or click "Debug" > "Stop Debugging" to stop debugging.
    9. 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 ...) )

Well, if you also like UWP development, or have any problems, you can join 193148992 to learn about communication ^_^.

--it Chase Dream Garden

UWP Dev: Teach you to add live tiles to your app

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.