Universal App - 操作 Tiles

Universal App - 操作 Tiles

在 WP7.1/8.0 的 App中的 Tile 方式,可參考:<Windows Phone 7 - 學習新的Secondary Tile與Application Tile>、

<Windows Phone 7 – 讓你的程式出現在Tile中也有功能 – Live Tile>與<Windows Phone 8 – Tiles大進化>。

 

開發 Universal App 時在針對 Live Tile 建立與操作採用不同的運作方法。

改由 XML 來設定,在建立時透過呼叫 GetTemplateContent 取得定義好的 XML 內文,再按照需求調整裡面的內容,

最後交給各自的 Manager 來觸發顯示。

 

開始針對可通知或顯示應用程式狀態的方式,加以說明如下:

〉Tiles

    可在 Start Screen 呈現應用程式資訊的元素,又被稱為“Live Tile” 表示它可以動態改變內容、資訊。

    一個 App 具有一個 Primary tile 與多個 Secondary tiles 可搭配使用,得以串聯應用程式中的畫面與顯示必要的內容。

    *Tile templates 針對 Tile 的呈現分成二種

       peek  tile:滾動上下畫面來顯示完整訊息的呈現方式,接近 WP 中的 Flip;

       static tile:固定顯示,沒有翻頁或是特效,預設 Tile 在建立時即是這種類型,藉由 tile notifications 來更新;

 

    *default tile

      支援多種 size:small、medium、wide、large。可顯示文字、圖像、程式名稱或 badges。

      程式安裝後即具有一個 Default tile 在 Start Screen,該 tile 則是 app 專案(app's manifest file)中的定義,如下圖:

 

      [注意]

      a. WP8.1 不支援 Tile 顯示 logo,badge 是顯示在右上角( Windows store app 在右下角, name 在左下角)。與Windows store app不相同。

      b. badge 並非所有的 Tile XML template 均支援,需要使用對應的 XML template 與 APIs 來更新。

      c. 如果 tile 的 image size 不對,用戶則無法調整 tile size 。

      d.  notifications 機制是利用「size-specific」來找對應的 Tile template。

            =>所以 manifest tile 只是定義使用 medium size,那 notification 使用了 wide tile template 則會無法成功更新 tile。

      e. default tile 可定義 background color,所以 tile 不需要給背景色以透明底為主,可搭配不同的情境藉由 notification 更新。

      f. notification 更新是由系統決定順序(亂數),不應該去依賴它的顯示順序;

 

      *secondary tiles

         允許用戶從 Start screen 直接執行 App 裡的特定畫面或功能。它是由 App 決定那些情境適合提供 pint to start 的功能,讓用戶執行或刪除。

         secondary tiles 獨立於 main app tile (default tile)之外,所以它的 notifications 也要額外建立。

         更多詳細可參考<Secondary tiles overview>。

 

      *cycling tile notifications

         預設一個 tile 顯示一個 notification 直到它過期或是有新的 notification 進來取代它

         當 app 支援 cycling 機制,系統將自動旋轉當前最多 5 個 notifications 來更新 tile

         通常在 notification queue 中最舊的 notification 會被新進的 notification 取代,但 notification 提供 tag 加以標記,可在新的

         notification 進來時指定 tag 來取代。例如:拍賣時就可以藉由這樣的方式,立即更新現在的競價值;

         tags 可用於防止 notification 過時。更詳細可參考:<How to use the notification queue with local notifications>。

 

 

〉BadgeBadge overview (Windows Runtime apps)

    用在 Tile 上顯示目前應用程式的狀態。除了支援熟悉的數字呈現外,還可以自訂義符號(small image (glyph))。

    使用 badge schemabadge update notification (BadgeUpdateManager.getTemplateContentBadgeNotification.content) 搭配。

 

 

〉Toast notifications

    是過去熟悉出現在畫面頂端,內容由左至右閱讀的訊息。屬於一種應用程式可用的通知訊息,採用種 pop-up 的通知方式,

    讓應用程式與 user 進行互動,包括:用戶在操作其他 app、在 start screen 上均可以收到。

    (ToastNotificationManager.getTemplateContent/ToastNotification.content/ Toast schema/ The toast template catalog (Windows Runtime apps).

 

 

〉Lock screen

    呈現訊息在設備鎖定幕面時。應用程式只能顯示文字代號在鎖定屏幕上的小 Tiles。

 

 

本篇針對 Tile 加以說明,另外 Tile 的更新機制與過去 ShellTile 或 TileData(FlipTileData/CycleTileData/IconicTileData)是不一樣的,

利用新的「notification mechanisms」支援更多情境下的更新方式,如下說明:

 

A. Local notifications

     只使用文字與目前在設備上的圖像。適用於在指定時間或必要時出現的通知。

 

B. Periodic notifications

     基於 cloud-based service 所定期呈現的通知,可使用文字與圖像。

 

C. Push notifications

     從 cloud server 經由 Windows Push Notification Services (WNS) 發送文字與圖像至指定設備。

 

D. Scheduled notifications

     定義一個排程顯示的通知。

 

預設 Periodic、Push 與 Scheduled 三種類型notification是具有三天期效的,超過就無效會被丟棄。但 Local 類型則不會有

但建議還是要設定過期日。因為有時notification是依賴時間需求的,與其花時間自行處理不如設定到期日。

這三種notification均可以協助在應用程式更新與建立相關元素(tiles, badge, toast)。其中toast notification更可以與WP8.1

新的「action center」加以互動,詳細可參考<Managing toast notifications in action center>。

 

   

往下開始說明如何操作 Tile template 來更新 default Tile;

 

Tile Schema

    tile 內容採用 XML 格式,基於 Windows 所定義的 The tile template catalog  列出所有可用的顯示文字與圖像,更可搭配 badge 使用。

可搭配 NotificationsExtensions library 將 xml 物件化來操作比較方便(建議),不然就是利用 string 來建立完整的 payload。

預設利用 TileUpdateManager.getTemplateContent 取得 Tile template 的 XML content,並加以修改其中的 text, image, language 等。

如要取得 non-default tile (或稱 Secondary Tile)的話,需先藉由 TileNotification.content 取得已存在的 Tile 內容加以修改。

 

template 裡所定義的 schema,如下:

Element Description
binding Specifies the tile template. Every notification should include one binding element for each supported tile size.
指定 tile template。每一個 notification 應該具有為每一種支援的 tile size 搭配一個 binding element 。
image Specifies an image used in the tile template. The supplied image should match the size and shape requirements for the specific template or image within that template.
在 tile template 設定一個圖片。使用的圖片應符合 size 與 shape 的需求,以支援 template 中的使用。
text Specifies text used in the tile template.
設定 tile template 中支援的 text。
tile Base tile element, which contains a single visual element.
基本 tile template 中的元素,用來包裝 visual element。
visual Contains multiple binding child elements, each of which defines a tile.
可包含多個 binding elements,每一個 binding element 定義要更新的 tile template。
代表可以同時更新多種不同 size 的 tile。

範例如下:

<tile>
  <visual>
    <binding template="TileSquareImage">
      <image id="1" src="image1" alt="alt text"/>
    </binding>  
  </visual>
</tile>
 
<tile>
  <visual version="2">
    <binding template="TileSquare150x150Image" fallback="TileSquareImage">
      <image id="1" src="image1" alt="alt text"/>
    </binding>  
  </visual>
</tile>

 

 

Tile Template Category

    The tile template catalog (Windows Runtime apps) 定義了各種不同 Size 與呈現方式的 Templates。但不是所有的Size都支援在 WP8.1 使用。

[注意]

* windows  與windows phone 的 style 很多均是排列的方式。

* icon 與image二種在WP8.1也分開定義。<Tile and toast image sizes.>

* TileSize:

  • Tiny (30x30) (Windows only)
  • Tiny (44x44) (Windows Phone only)
  • Small (70x70) (Windows only)
  • Small (71x71) (Windows Phone only)
  • Medium (150x150)
  • Large (310x310) (Windows only)

 

 

TileUpdateManager

     負責建立 TileUpdater 物件來改變與更新 Start 畫面中的 Tiles 與提供連結 system-provided 的 tile template 。

主要方法如下:

Method Description
CreateTileUpdaterForApplication 建立與初始化一個新的 TileUpdater  instance 讓程式來呼叫更新 app 的 tile。
CreateTileUpdaterForApplication(applicationId) 藉由指定相同 package 下的  applicationId 來建立與初始化一個新的 TileUpdater instance。讓開發者可以更新自己 app 以外的 tile。
使用上需注意:

This method is used only in conjunction with multi-app packages. The app identified by applicationId must belong to the same package as the caller.

Although you can specify the calling application's tile in this method, createTileUpdaterForApplication is the preferred method to use with single-app packages.

CreateTileUpdaterForSecondaryTile(tileId) 建立與初始化一個新的 TileUpdater  instance 讓程式來呼叫更新 secondary tile。
secondary tile 能被所屬於相同 package 下的 app 或其他 app 呼叫更新。
建立與更新 secondary tile 需要給一個 tile id。
GetTemplateContent(TileTemplateType) 利用 TileTemplateType 列舉取得系統提供的 tile template。內容為 XmlDocument

 

 

TileUpdater

     負責更新指定 tile 的內容。重點與屬性方法如下:

Type Name Description
Methods AddToSchedule Adds a ScheduledTileNotification to the schedule.
  Clear Removes all updates and causes the tile to display its default content as declared in the app's manifest.
  EnableNotificationQueue Enables the tile to queue up to five notifications. This enables the notification queue on all tile sizes.
  EnableNotificationQueueForSquare150x150 Enables the tile to queue up to five notifications on the medium tile.
  EnableNotificationQueueForSquare310x310 Enables the tile to queue up to five notifications on the large tile.
  EnableNotificationQueueForWide310x150 Enables the tile to queue up to five notifications on the wide tile.
  GetScheduledTileNotifications Retrieves a list of scheduled updates to the tile.
  RemoveFromSchedule Removes an upcoming tile update from the schedule.
  StartPeriodicUpdate(Uri,DateTime,PeriodicUpdateRecurrence) Begins a series of timed updates for the tile that the updater is bound to. Update content is retrieved from a specified Uniform Resource Identifier (URI). Updates begin at a specified time.
  StartPeriodicUpdate(Uri,PeriodicUpdateRecurrence) Begins a series of timed content changes for the tile that the updater is bound to, beginning immediately.
  StartPeriodicUpdateBatch(IIterable(Uri),DateTime,PeriodicUpdateRecurrence) Begins a series of timed updates that cycle on the tile that the updater is bound to. Update content is retrieved from an array of specified Uniform Resource Identifier (URI) with updates beginning at a specified time and subsequent updates occurring at the periodic interval thereafter.
  StartPeriodicUpdateBatch(IIterable(Uri),PeriodicUpdateRecurrence) Begins a series of timed updates that cycle on the tile that the updater is bound to. Update content is retrieved from an array of specified Uniform Resource Identifier (URI), the first update happening immediately and subsequent updates occurring at the periodic interval thereafter.
  StopPeriodicUpdate Cancels the current series of timed updates for the tile that the updater is bound to.
  Update Applies a change in content or appearance to the tile.
Properties Setting Read-only. Gets a value that specifies whether a tile can be updated through notifications.

上述的功能非常多本篇只針對 Update() 來說明,相關如何設定支援 ScheduleTile 與 PeriodicUpdate 則由下篇說明。

 

 

TileNotification

     定義一個 Tile 的更新單位,裡面包括 visuals, identification tag, and expiration time。重要屬性與方法如下:

Type Name Description
Constructor TileNotification(XmlDocument) Creates and initializes a new instance of the TileNotification object for use with a TileUpdater.
Property Content Read-only. Gets the XML description of the notification content, which you can then manipulate to alter the notification.
  ExpirationTime Read/write. Gets or sets the time that Windows will remove the notification from the tile
By default, a tile update does not expire. It is a best practice to explicitly set an expiration time to avoid stale content.
  Tag Read/write. Gets or sets a string that Windows can use to prevent duplicate notification content from appearing in the queue.

ExpirationTime 建議可以設定讓 Tile 的更新不會一直保持在與進入後 App 內容不相符合的狀況,例如:播放 A 這種歌,但已經換到 B 了,Tile 還

仍然是 A。Tag 建議設定,尤其如果需要操作 Queue 的功能時該屬性值有助於識別。

 

以上介紹了 Tile 更新的重要元素與相關類別,以下將透過範例介紹如何操作:

A. 利用 XML 結構一次更新三種不同 template 的 Tiles

     這次要更新的 tile 有三種類型:TileSquare150x150PeekImageAndText01、TileWide310x150PeekImage02、TileSquare310x310ImageAndTextOverlay03。

但是因為 Windows Phone  不支援 TileSquare310x310ImageAndTextOverlay03,所以換另一種:TileWidePeekImageCollection02。

三種合併讓 Tile 不管在用戶設定為何種 Size 均可以得到更新後的資訊。

 

a-1. 準備需要的圖像與對應的 Size;

template name properties
TileSquare150x150PeekImageAndText01 image
支援四種類型。AndText01、AndText02、AndText03、AndText04,Text 差別在於數量與折行的方式。
圖片的大小依照:template 宣告的類型,例如:Square150x150,代表:預設 150x150,不同的 size 比例如下:
image
Windows Phone 請多準備一個 240% (360x360)
TileWide310x150PeekImage02 image
Top/Front: One wide image. Bottom/Back: One header string in larger text on the first line, four strings of regular text on the next four lines. Text does not wrap.
TileSquare310x310ImageAndTextOverlay03 image
Background: a single image that fills the entire tile. Foreground: At the top, one string of large text wrapped over a maximum of two lines; at the bottom, three strings of regular text on three lines that do not wrap. If the text color is light, the image is darkened a bit to improve the text visibility.
TileWidePeekImageCollection02 image

Windows: Top: One large square image with four smaller square images to its right, no text. Note that the large image is not quite square; it is slightly wider than it is tall. If you supply a square image, the image will be scaled for width and slightly cropped on the top and bottom.

Windows Phone 8.1: Front: The images appear in a 6x3 set of tessellated, flipping blocks. An image might take up one block or four. Images are shown randomly, moving among blocks of various solid colors.

Bottom/Back: One header string in larger text on the first line, four strings of regular text on the next four lines. Text does not wrap.

image

Windows App 需要先至 package.appxmanifest 設定 Wide310x150 logo 與 Square310x310 logo 的圖示,如下:

00

 

 

a-2. 遂一取得 tile template 與指定更新的值,並加以合併三種不同的 tile template;

public static void UpdateDefaultTile()
{
    // 準備要更新 tile 的內容與圖示
    String[] text = new String[] { "Text Field 1 (larger text)", "Text Field 2", "Text Field 3", "Text Field 4" };
    String imgPath = "ms-appx:///Assets/Tiles/05.png";
    String imgAlt = "default image";
    Dictionary<String, String> imgCollection = new Dictionary<string, string>
    {
        {"img0","ms-appx:///Assets/Tiles/01.png"},
        {"img1","ms-appx:///Assets/Tiles/02.png"},
        {"img2","ms-appx:///Assets/Tiles/03.png"},
        {"img3","ms-appx:///Assets/Tiles/04.png"},
    };
 
    // TileUpdater 清掉所有的 tile update 內容。
    TileUpdateManager.CreateTileUpdaterForApplication().Clear();
 
    // 準備要使用的 tile template
    TileTemplateType[] types = new TileTemplateType[] {
        TileTemplateType.TileSquare150x150PeekImageAndText01,
#if WINDOWS_APP
        TileTemplateType.TileWide310x150PeekImage02,
        TileTemplateType.TileSquare310x310ImageAndTextOverlay03
#endif 
#if WINDOWS_PHONE_APP
        TileTemplateType.TileWidePeekImageCollection02
#endif
    };
 
    XmlDocument tileDom = new XmlDocument();
 
    foreach (var tileType in types)
    {
        // get template
        XmlDocument tileTemplateDom = TileUpdateManager.GetTemplateContent(tileType);
        // feed text elements
        XmlNodeList textXmls = tileTemplateDom.GetElementsByTagName("text");
        for (int i = 0; i < text.Length; i++)
        {
            if (textXmls.Length - 1 >= i)
            {
                textXmls[i].InnerText = text[i];
            }
        }
 
        XmlNodeList tileImageAttributes = tileTemplateDom.GetElementsByTagName("image");
        if (tileType != TileTemplateType.TileWidePeekImageCollection02)
        {
            ((XmlElement)tileImageAttributes[0]).SetAttribute("src", imgPath);
            ((XmlElement)tileImageAttributes[0]).SetAttribute("alt", imgAlt);
        }
        else
        {
            for (int i = 0; i < imgCollection.Count; i++)
            {
                String key = String.Format("img{0}", i);
                ((XmlElement)tileImageAttributes[i]).SetAttribute("src", imgCollection[key]);
                ((XmlElement)tileImageAttributes[i]).SetAttribute("alt", key);
            }
        }
 
        if (tileDom.HasChildNodes() == false)
        {
            tileDom = tileTemplateDom;
        }
        else
        {
            // 合併多個 tile template
            IXmlNode node = tileDom.ImportNode(tileTemplateDom.GetElementsByTagName("binding").Item(0), true);
            tileDom.GetElementsByTagName("visual").Item(0).AppendChild(node);
        }
    }
    // 取得要求更新的 TileNotification
    TileNotification tile = new TileNotification(tileDom);
    // 取得 TileUpdater 發送更新
    TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
}

 

a-4. 執行結果:

Windows:

未命名

Windows Phone:

11

TileWide310x150PeekImage02 與 TileWidePeekImageCollection02 屬同一種 Wide 類型,故選擇 TileWidePeekImageCollection02 來呈現。

 

 

[範例程式]

http://1drv.ms/15zX9EQ

======

寫到這裡算是把新的Tiles給介紹完了,其實還有很多內容可參考我下方的 References,有些我自己正還在讀。

希望先幫大家整理相關 Universal App 操作 Tile 時要注意的地方。如果有撰寫不好的地方,也請多指教,謝謝。

 

References

Guidelines for tiles and notifications (重要)

Working with tiles, badges, and toast notifications (Windows Runtime apps using JavaScript and HTML) (重要)

Tiles, badges, and notifications (Windows Runtime apps) (重要概念)

Windows Phone 8.1 for Developers–Overview

Quickstart: Creating a default tile using the Microsoft Visual Studio manifest editor (Windows Runtime apps) (重要)

Quickstart: Showing tile and badge updates on the lock screen (Windows Runtime apps)

Windows Phone 8.1 for Developers–Live Tiles

Windows Phone 8.1 samples

//Build/ 2014 Windows Phone 8.1 重點Session 整理

File access sample & Geolocation sample

Managing toast notifications in action center

Using live tiles with different app types (Windows Runtime apps) (重要觀念)

The tile template catalog (Windows Runtime apps) (重要)

Using NotificationsExtensions

   (協助供應tile, badge, toast notification XML template content,在不透過XML DOM的情況提供一個直接操作的方式。)

Creating tiles and badges

   (如何定義tile或badge content與傳送notification需要的content。content採用local notification,

    更包括傳送scheduled、periodic與push。)

Pinning secondary tiles

   (指導如何pin secondary tiles與操作其中的content。與如何直接操作start screen中的content。)

Sending toast notifications

   (如何定義與傳送toast notification,它是一種pop-up的通知允許應用程式與user進行互動,包括:

   用戶在操作其他app、在start screen上均可以收到。使用的notification類型也包括了local notification與其他參數。)

Delivering notifications

Troubleshooting tile, toast, and badge notifications

How to vibrate a Windows Phone device

Developers: Make your Tiles Transparent for Windows Phone 8.1

Guidelines for tiles and badges & App tiles and badges sample (重要)

 

Dotblogs Tags: ,