我的 Live Tile 正在跟踪自 3 种类型的事件以来的时间:Event1、Event2、Event3。我希望实时磁贴显示事件发生后的时间。
我在后台任务中实现了它,如下面的代码,我想知道它是否是正确的方法?
我看到的所有示例都调用了一次 Run,因此 AddTileNotification 只调用了一次。我将其修改为在 While(true) 循环中,不确定吗?!
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
namespace BackgroundTasks
{
public sealed class TileUpdaterClass : IBackgroundTask
{
TileUpdater tileUpdater;
public void Run( IBackgroundTaskInstance taskInstance )
{
while ( true )
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
tileUpdater.EnableNotificationQueue( true );
AddTileNotification( "Since Event1: " + TimeSince( "Event1" ), "tag1", "ms-appx:///Resources/Images/Event1.jpg" );
AddTileNotification( "Since Event2: " + TimeSince( "Event2" ), "tag2", "ms-appx:///Resources/Images/Event2.jpg" );
AddTileNotification( "Since Event3: " + TimeSince( "Event3" ), "tag3", "ms-appx:///Resources/Images/Event3.jpg" );
deferral.Complete();
Task.Delay( 5000 );
}
}
private static string TimeSince( string key )
{
TimeSpan since;
if ( ApplicationData.Current.LocalSettings.Values.ContainsKey( key ) )
{
since = new TimeSpan( DateTime.Now.Ticks - ( new DateTime( (long)ApplicationData.Current.LocalSettings.Values[ key ] ) ).Ticks );
}
return ( since.Hours.ToString( "D2" ) + ":" + since.Minutes.ToString( "D2" ) + ":" + since.Seconds.ToString( "D2" ) );
}
private void AddTileNotification( string content, string tag, string image )
{
var templateType = TileTemplateType.TileWideSmallImageAndText04;
var xml = TileUpdateManager.GetTemplateContent( templateType );
var textNodes = xml.GetElementsByTagName( "text" );
textNodes[ 0 ].AppendChild( xml.CreateTextNode( "myApp" ) );
textNodes[ 1 ].AppendChild( xml.CreateTextNode( content ) );
var imageNodes = xml.GetElementsByTagName( "image" );
var elt = (XmlElement)imageNodes[ 0 ];
elt.SetAttribute( "src", image );
var tile = new TileNotification( xml );
tile.Tag = tag;
tileUpdater.Update( tile );
}
}
}
我还注意到磁贴没有按顺序显示 3 个事件。时间保持正确,但顺序不正确。正常吗?
谢谢, EitanB