[Azure]使用Mobile Service的推播功能
摘要
不管是Line或是Facebook您一定都有收到即時訊息的通知,而這種通知就是推播功能,
這邊將教大家如何使用Microsoft Azure上的Mobile Service快速做出推播功能!
實作
1. 開啟上次快速產生的ToDoList檔案的App.xaml.cs
2. 加入 using Microsoft.Phone.Notification;
3. 然後註冊我們的推播通知
public static HttpNotificationChannel CurrentChannel { get; private set; }
private void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
CurrentChannel.BindToShellToast();
}
CurrentChannel.ChannelUriUpdated +=
new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
// Register for notifications using the new channel
await MobileService.GetPush()
.RegisterNativeAsync(CurrentChannel.ChannelUri.ToString());
});
}
4. 在public App() {}裡加入 AcquirePushChannel(); 確保登記請求每次加載頁面的時間。
5. 接著開啟 WMAppMainfest.xml 並勾選 IDCAPPUSH_NOTIFICATION 。
6. 回到Azure上面並更改資料表的指令碼,發送一個推播通知。
function insert(item, user, request) {
// Define a payload for the Windows Phone toast notification.
var payload = '<?xml version="1.0" encoding="utf-8"?>' +
'<wp:Notification xmlns:wp="WPNotification"><wp:Toast>' +
'<wp:Text1>New Item</wp:Text1><wp:Text2>' + item.text +
'</wp:Text2></wp:Toast></wp:Notification>';
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.mpns.send(null, payload, 'toast', 22, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
}
});
}
7. 點選 "推送" 並勾選 "啟用未經驗證的推送通知"。
8. 執行之後 按下 "Save" 之後 ""立刻"" 按下 返回鍵 或是 開始鍵 就可以看到推播了!!!
參考資料