由推播通知精靈產生的程式碼

您可以藉由 Visual Studio 中的精靈,從利用 Azure 行動服務建立的行動服務產生推播通知。 Visual Studio 精靈會產生程式碼,協助您開始使用。 這個主題說明精靈如何修改您的專案、所產生的程式碼如何作用、如何使用此程式碼,以及如何進一步充分利用推播通知。 請參閱 Windows 推播通知服務 (WNS) 概觀

精靈如何修改您的專案

推播通知精靈會透過下列方式修改您的專案:

  • 將參考新增至行動服務受控用戶端 (MobileServicesManagedClient.dll)。 不適用 JavaScript 專案。
  • 在服務下的子資料夾中新增檔案,並將檔案命名為 push.register.cs、push.register.vb、push.register.cpp 或 push.register.js。
  • 在資料庫伺服器上建立行動服務的通道表。 此表包含將推播通知傳送至應用程式執行個體所需的資訊。
  • 建立四項功能的指令碼:刪除、插入、讀取和更新。
  • 使用自訂 API notifyallusers.js 建立指令碼,以將推播通知傳送給所有用戶端。
  • 新增宣告至 App.xaml.cs、App.xaml.vb 或 App.xaml.cpp 檔案,若是 JavaScript 專案,則新增宣告至新檔案 service.js。 宣告會宣告 MobileServiceClient 物件,該物件中包含連線至行動服務所需的資訊。 您可以使用這個名稱 App.MyServiceNameClient,從應用程式中的任何頁面存取名為 MyServiceNameClient 的 MobileServiceClient 物件。

services.js 檔案包含下列程式碼:

var <mobile-service-name>Client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
                "https://<mobile-service-name>.azure-mobile.net/",
                "<your client secret>");

推播通知的註冊

在 push.register.* 中,UploadChannel 方法會註冊裝置以接收推播通知。 商店會追蹤安裝的應用程式執行個體,並提供推播通知通道。 請參閱 PushNotificationChannelManager

JavaScript 後端與 .NET 後端的用戶端程式碼類似。 根據預設,當您新增 JavaScript 後端服務的推播通知時,UploadChannel 方法內會插入 notifyAllUsers 自訂 API 的範例呼叫。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;

namespace App2
{
    internal class mymobileservice1234Push
    {
        public async static void UploadChannel()
        {
            var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            try
            {
                await App.mymobileservice1234Client.GetPush().RegisterNativeAsync(channel.Uri);
                await App.mymobileservice1234Client.InvokeApiAsync("notifyAllUsers");
            }
            catch (Exception exception)
            {
                HandleRegisterException(exception);
            }
        }

        private static void HandleRegisterException(Exception exception)
        {
            
        }
    }
}
Imports Microsoft.WindowsAzure.MobileServices
Imports Newtonsoft.Json.Linq

Friend Class mymobileservice1234Push
    Public Shared Async Sub UploadChannel()
        Dim channel = Await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync()

        Try
            Await App.mymobileservice1234Client.GetPush().RegisterNativeAsync(channel.Uri)
            Await App.mymobileservice1234Client.GetPush().RegisterNativeAsync(channel.Uri, New String() {"tag1", "tag2"})
            Await App.mymobileservice1234Client.InvokeApiAsync("notifyAllUsers")
        Catch exception As Exception
            HandleRegisterException(exception)
        End Try
    End Sub

    Private Shared Sub HandleRegisterException(exception As Exception)

    End Sub
End Class
#include "pch.h"
#include "services\mobile services\mymobileservice1234\mymobileservice1234Push.h"

using namespace AzureMobileHelper;

using namespace web;
using namespace concurrency;

using namespace Windows::Networking::PushNotifications;

void mymobileservice1234Push::UploadChannel()
{
    create_task(PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync()).
    then([] (PushNotificationChannel^ newChannel) 
    {
        return mymobileservice1234MobileService::GetClient().get_push().register_native(newChannel->Uri->Data());
    }).then([]()
    {
        return mymobileservice1234MobileService::GetClient().invoke_api(L"notifyAllUsers");
    }).then([](task<json::value> result)
    {
        try
        {
            result.wait();
        }
        catch(...)
        {
            HandleExceptionsComingFromTheServer();
        }
    });
}

void mymobileservice1234Push::HandleExceptionsComingFromTheServer()
{
}
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.addEventListener("activated", function (args) {
        if (args.detail.kind == activation.ActivationKind.launch) {
            Windows.Networking.PushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync()
                .then(function (channel) {
                    mymobileserviceclient1234Client.push.registerNative(channel.Uri, new Array("tag1", "tag2"))
                    return mymobileservice1234Client.push.registerNative(channel.uri);
                })
                .done(function (registration) {
                    return mymobileservice1234Client.invokeApi("notifyAllUsers");
                }, function (error) {
                    // Error

                });
        }
    });
})();

推播通知標籤提供了將通知限於一部分用戶端的方式。 您可以使用 registerNative 方法 (或 RegisterNativeAsync) 來註冊所有推播通知但不指定標籤,或是藉由提供第二個引數 (也就是標籤陣列) 來使用標籤註冊。 如果您使用一或多個標籤註冊,則只會收到符合這些標籤的通知。

伺服器端指令碼 (僅適用 JavaScript 後端)

若是使用 JavaScript 後端的行動服務,伺服器端指令碼會在刪除、插入、讀取或更新作業發生時執行。 指令碼不會實作這些作業,但會在從用戶端呼叫 Windows Mobile REST API 以觸發這些事件時執行。 接著指令碼會藉由呼叫 request.execute 或 request.response 對呼叫端內容發出回應,將控制項傳遞至作業本身。 請參閱 Azure 行動服務 REST API 參考

伺服器端指令碼中提供了各式各樣的函式。 請參閱在 Azure 行動服務中註冊表格作業。 如需所有可用函式的參考,請參閱行動服務伺服器指令碼參考

另外也會建立下列 Notifyallusers.js 中的自訂 API 程式碼:

exports.post = function(request, response) {
    response.send(statusCodes.OK,{ message : 'Hello World!' })
    
    // The following call is for illustration purpose only
    // The call and function body should be moved to a script in your app
    // where you want to send a notification
    sendNotifications(request);
};

// The following code should be moved to appropriate script in your app where notification is sent
function sendNotifications(request) {
    var payload = '<?xml version="1.0" encoding="utf-8"?><toast><visual><binding template="ToastText01">' +
        '<text id="1">Sample Toast</text></binding></visual></toast>';
    var push = request.service.push; 
    push.wns.send(null,
        payload,
        'wns/toast', {
            success: function (pushResponse) {
                console.log("Sent push:", pushResponse);
            }
        });
}

sendNotifications 函式會將單一通知做為快顯通知傳送。 您也可以使用其他類型的推播通知。

提示:如需如何在編輯指令碼時取得協助的相關資訊,請參閱為伺服器端 JavaScript 啟用 IntelliSense

 

推播通知類型

Windows 支援不是推播通知的通知。 如需有關通知的一般資訊,請參閱選擇通知傳遞方法

快顯通知很容易使用,您可以在為您產生的通道表上檢閱 Insert.js 中的範例。 如果您打算使用磚或徽章通知,則必須建立磚和徽章的 XML 範本,而且您必須指定範本中封裝資訊的編碼方式。 請參閱使用磚、徽章和快顯通知

由於 Windows 會回應推播通知,因此可以在應用程式未執行時,處理大部分的通知。 例如,即使本機郵件應用程式未執行,推播通知也能讓使用者得知有新的郵件訊息。 Windows 會藉由顯示訊息來處理快顯通知,例如,簡訊的第一行。 Windows 會藉由更新應用程式的動態磚來反映新郵件訊息的數目,以處理磚或徽章通知。 如此一來,您就可以提示應用程式的使用者查看是否有新資訊。 您的應用程式可在執行時接收原始通知,您可以使用這些通知將資料傳送至您的應用程式。 如果您的應用程式未執行,您可以設定背景工作來監視推播通知。

您應根據 Windows 應用程式的指導方針使用推播通知,因為這些通知會佔用使用者的資源,而且過度使用可能會造成分心。 請參閱推播通知的指導方針和檢查清單

如果您要使用推播通知更新動態磚,則也應遵循磚和徽章的指導方針和檢查清單中的指導方針。

下一步

使用 Windows 推播通知服務 (WNS)

如果行動服務未提供足夠的彈性、您想要使用 C# 或 Visual Basic 撰寫伺服器程式碼,或是您已有雲端服務並且想要從該服務傳送推播通知,您可以直接呼叫 Windows 推播通知服務 (WNS)。 直接呼叫 WNS 就可以從自己的雲端服務傳送推播通知,例如,監視來自資料庫或其他 Web 服務的資料的背景工作角色。 您的雲端服務必須使用 WNS 進行驗證,才能將推播通知傳送至您的應用程式。 請參閱如何使用 Windows 推播通知服務 (JavaScript)(C#/C++/VB) 進行驗證。

您也可以在行動服務中執行排程工作來傳送推播通知。 請參閱在行動服務中排程週期性工作

警告:一旦您執行過推播通知精靈一次,則切勿再次執行精靈來新增另一項行動服務的註冊碼。 若每個專案執行精靈一次以上,則會產生程式碼而導致對 CreatePushNotificationChannelForApplicationAsync 方法的呼叫重疊,進而造成執行時期發生例外狀況。 如果您想要註冊多項行動服務的推播通知,請執行精靈一次,然後重新寫入註冊碼,以確保對 CreatePushNotificationChannelForApplicationAsync 的呼叫不會同時執行。 例如,您可以將精靈在 push.register.* 中產生的代碼 (包括對 CreatePushNotificationChannelForApplicationAsync 的呼叫) 移到 OnLaunched 事件外來完成此操作,但具體細節將取決於應用程式的架構。