共用方式為


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

在 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 方法會註冊裝置以接收推播通知。 商店會追蹤您應用程式的已安裝實例,並提供推送通知通道。 See 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 應用程式的指導方針使用推播通知,因為這些通知會佔用使用者的資源,而且過度使用可能會造成分心。 如需推播通知,請參閱 指導方針和檢查清單。

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

Next steps

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

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

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

警告:一旦您執行過推播通知精靈一次,則切勿再次執行精靈來新增另一項行動服務的註冊碼。 在每個專案中多次執行精靈會產生程式碼,這會導致重複呼叫 CreatePushNotificationChannelForApplicationAsync 方法,從而引發執行時期異常。 如果您想為多個行動服務註冊推播通知,請先執行向導一次,然後重寫註冊程式碼,以確保呼叫 CreatePushNotificationChannelForApplicationAsync 不會同時進行。 例如,您可以將向導生成的程式碼(包括對 CreatePushNotificationChannelForApplicationAsync的呼叫)移動到 OnLaunched 事件外部來達成此目的,但具體細節將取決於您的應用程式架構。