微软云技术Windows Azure专题(三):如何利用Mobile向Windows商店应用推送消息(2)


 

   

 

 

第一步:上一讲的所有操作

 

第二步:建立一个通道表(Channel)

 

第三步:修改Windows商店应用的代码

public class TodoItem
{
    public int Id { get; set; }


[JsonProperty(PropertyName = "text")]
public string Text { get; set; }


[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }


}


ButtonSave函数修改成

private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    var todoItem = new TodoItem { Text = TextInput.Text };
    InsertTodoItem(todoItem);
}

 

添加一个Channel类

public class Channel
{
    public int Id { get; set; }


[JsonProperty(PropertyName = "uri")]
public string Uri { get; set; }


}

 

AcquirePushChannel函数

private async void AcquirePushChannel()
{
   CurrentChannel = 
       await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();


   IMobileServiceTable<Channel> channelTable = App.MobileService.GetTable<Channel>();
   var channel = new Channel { Uri = CurrentChannel.Uri };
   await channelTable.InsertAsync(channel);
}


 

第三步:修改Mobile Service的脚本

function insert(item, user, request) {
    var channelTable = tables.getTable('Channel');
    channelTable
        .where({ uri: item.uri })
        .read({ success: insertChannelIfNotFound });
    function insertChannelIfNotFound(existingChannels) {
        if (existingChannels.length > 0) {
            request.respond(200, existingChannels[0]);
        } else {
            request.execute();
        }
    }
}

function insert(item, user, request) {
    request.execute({
        success: function() {
            request.respond();
            sendNotifications();
        }
    });


function sendNotifications() {
    var channelTable = tables.getTable('Channel');
    channelTable.read({
        success: function(channels) {
            channels.forEach(function(channel) {
                push.wns.sendToastText04(channel.uri, {
                    text1: item.text
                }, {
                    success: function(pushResponse) {
                        console.log("Sent push:", pushResponse);
                    }
                });
            });
        }
    });
}
}


第五步:测试应用



相关内容