Windows phone 8 study notes (5) block diagram and notice

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Metro style Windows phone 8 Application mentioned a concept map based on the block, it refers to the quick launch icon to start menu. Usually an application must have a default block, can also have several secondary block. In addition, the close relation between notification and blocks, we can receive messages to dynamically update the blocks to achieve timely effect. We this section to block and notice put together.

Fast navigation:
A, block
Two, block update schedule
Three, local notice
Four, push notification

A, block

1)To define the default block

The default block can only define it in the list of files, and the selected block template cannot be changed, unless the re release, but we can update the same type of template. Application after installing the default state does not appear in the start menu, right-click on the program list to choose fixed to the start screen items.

Block template type:
   The 1 Icon template: It contains two kinds of icon, three blocks can be used. Must include a transparent background PNG format Metro style.
   The 2 turning template: In the middle, large block can be achieved in the overturning effect.
   3 circular template: To achieve a background image in the middle, turn switch large blocks of.

2)Create update block

Create and update can be two ways to block, respectively is the build definitions template XML or through the code, the code below demonstrates how to create and update block.

[C#]
public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); // For localization ApplicationBar The sample code //BuildLocalizedApplicationBar(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); } private void Button_Click_1(object sender, RoutedEventArgs e) { CreateTitle(); } private void ShowTitle() { var tilte = ShellTile.ActiveTiles.FirstOrDefault(); if (tilte != null) { MessageBox.Show(tilte.NavigationUri.ToString()); } } //Icon block IconicTileData iconicTileData = new IconicTileData() { Title = "Title", Count = 5, WideContent1 = "The first line of text", WideContent2 = "Second lines of text", WideContent3 = "Third lines of text", SmallIconImage = new Uri("/Assets/Tiles/IconLarge.png", UriKind.Relative), IconImage = new Uri("/Assets/Tiles/IconSamall.png", UriKind.Relative), //Set the transparency to255Will display a custom background color, Otherwise display system BackgroundColor = new Color { A = 255, R = 0, G = 148, B = 255 } }; //Icon block template string iconicTileXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <wp:Notification xmlns:wp=""WPNotification"" Version=""2.0""> <wp:Tile Id=""titleid1"" Template=""IconicTile""> <wp:SmallIconImage>/Assets/Tiles/IconLarge.png</wp:SmallIconImage> <wp:IconImage>/Assets/Tiles/IconSamall.png</wp:IconImage> <wp:WideContent1>The first line of text</wp:WideContent1> <wp:WideContent2 Action=""Clear"">Second lines of text</wp:WideContent2> <wp:WideContent3>Third lines of text</wp:WideContent3> <wp:Count>6</wp:Count> <wp:Title>Title</wp:Title> <wp:BackgroundColor>#FF524742</wp:BackgroundColor> </wp:Tile> </wp:Notification>"; //Can be used for cleaningCount(如果加了Action="Clear",Clear display of the item) string iconicTileXml2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <wp:Notification xmlns:wp=""WPNotification"" Version=""2.0""> <wp:Tile Id=""titleid1"" Template=""IconicTile""> <wp:Count Action=""Clear"">0</wp:Count> </wp:Tile> </wp:Notification>"; //Flip block FlipTileData flipTileData = new FlipTileData() { Title = "Title", BackTitle = "On the back of the title", BackContent = "The back part of the text", WideBackContent = "In the text block back width", Count = 5, SmallBackgroundImage = new Uri("/Assets/Tiles/Samall.png", UriKind.Relative), BackgroundImage = new Uri("/Assets/Tiles/Medium.png", UriKind.Relative), //Don't set the background image is displayed as the background color //BackBackgroundImage = new Uri("Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative), WideBackgroundImage = new Uri("/Assets/Tiles/Large.png", UriKind.Relative), //WideBackBackgroundImage = new Uri("/Assets/Tiles/IconicTileMediumLarge.png", UriKind.Relative) }; //Flip block template string flipTileXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <wp:Notification xmlns:wp=""WPNotification"" Version=""2.0""> <wp:Tile Id=""titleid2"" Template=""FlipTile""> <wp:SmallBackgroundImage>/Assets/Tiles/Samall.png</wp:SmallBackgroundImage> <wp:WideBackgroundImage>/Assets/Tiles/Large.png</wp:WideBackgroundImage> <wp:WideBackBackgroundImage>/Assets/Tiles/IconicTileMediumLarge.png</wp:WideBackBackgroundImage> <wp:WideBackContent>In the text block back width</wp:WideBackContent> <wp:BackgroundImage>/Assets/Tiles/Medium.png</wp:BackgroundImage> <wp:Count>6</wp:Count> <wp:Title>Title</wp:Title> <wp:BackBackgroundImage>Assets/Tiles/FlipCycleTileMedium.png</wp:BackBackgroundImage> <wp:BackTitle>On the back of the title</wp:BackTitle> <wp:BackContent>The back part of the text</wp:BackContent> </wp:Tile> </wp:Notification>"; //Cyclic block CycleTileData cycleTileData = new CycleTileData() { Title = "Title", Count = 10, SmallBackgroundImage = new Uri("/Assets/Tiles/Samall.png", UriKind.Relative), CycleImages = new Uri[] { new Uri("/Assets/Tiles/Title1.png", UriKind.Relative), new Uri("/Assets/Tiles/Title2.png", UriKind.Relative), new Uri("/Assets/Tiles/Title3.png", UriKind.Relative), } }; //Cyclic block template string cycleTileXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <wp:Notification xmlns:wp=""WPNotification"" Version=""2.0""> <wp:Tile Id=""titleid3"" Template=""CycleTile""> <wp:SmallBackgroundImage>/Assets/Tiles/Samall.png</wp:SmallBackgroundImage> <wp:CycleImage1>/Assets/Tiles/Title1.png</wp:CycleImage1> <wp:CycleImage2>/Assets/Tiles/Title2.png</wp:CycleImage2> <wp:CycleImage3>/Assets/Tiles/Title3.png</wp:CycleImage3> <wp:Count>6</wp:Count> <wp:Title>Title</wp:Title> </wp:Tile> </wp:Notification>"; private void CreateTitle() { //Add a secondary block ShellTile.Create(new Uri("/Page1.xaml", UriKind.Relative), iconicTileData, true); //ThroughxmlTemplate to add ShellTile.Create(new Uri("/Page1.xaml", UriKind.Relative), new IconicTileData(iconicTileXml), true); } private void ClearCount() { //EliminateCount ShellTile.ActiveTiles.ElementAt(1).Update(new IconicTileData(iconicTileXml2)); } private void UpdateTitle() { //Update the default block content, Flip the template we defined, Here cannot modify the template type ShellTile.ActiveTiles.FirstOrDefault().Update(flipTileData); } }

Two, block update schedule

We can define a renewal plan, update the background image of the regular block. When applied after the exit, the update program can run in the background. Its implementation code is as follows:

[C#]
ShellTileSchedule SampleTileSchedule = new ShellTileSchedule(); //Whether the plan has been executed bool TileScheduleRunning = false; //Begin to execute the plan private void Button_Click_1(object sender, RoutedEventArgs e) { //The specified program execution once or many times SampleTileSchedule.Recurrence = UpdateRecurrence.Interval; //The specified program update interval SampleTileSchedule.Interval = UpdateInterval.EveryHour; //The specified program execution times, If you do not set, For uncertain times SampleTileSchedule.MaxUpdateCount = 50; //The specified start time plan SampleTileSchedule.StartTime = DateTime.Now; //To obtain the background image networkURI SampleTileSchedule.RemoteImageUri = new Uri(@"http://images.cnblogs.com/cnblogs_com/lipan/319399/o_Large.png"); SampleTileSchedule.Start(); } //Stop planning private void Button_Click_2(object sender, RoutedEventArgs e) { if (TileScheduleRunning) SampleTileSchedule.Stop(); }

Three, local notice

Notice is divided into local notifications and push notifications. We can realize local news and local notice reminding function.

1)Local news and remind

We can define the warning and alarm clock function, in the application to quit after, when the time is reached, alert or alarm will automatically do not trigger the alarm clock function, we can also custom ringtones. Have a look below the process code.

[XAML]
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="listbox1" Width="440" MaxHeight="420" Margin="10,44,0,150"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Background="Blue" Width="440"> <TextBlock Width="120" Text="{Binding Title}" /> <TextBlock Text="{Binding BeginTime}" /> <TextBlock Text="{Binding RecurrenceType}" /> <TextBlock Text=" " /> <TextBlock Text="{Binding IsScheduled}" /> <TextBlock Text=" " /> <Button Margin="0" Tag="{Binding Name}" Click="deleteButton_Click" Content="X" BorderBrush="Red" Background="Red" Foreground="{StaticResource PhoneBackgroundBrush}" VerticalAlignment="Top" BorderThickness="0" Width="50" Padding="0,0,0,0"></Button> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Margin" Value="5"/> </Style> </ListBox.ItemContainerStyle> </ListBox> <TextBlock HorizontalAlignment="Left" Margin="10,12,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="Local message registered remind: "> </TextBlock> <TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="72" Margin="10,555,0,0" TextWrapping="Wrap" Text="Title" VerticalAlignment="Top" Width="125"/> <RadioButton x:Name="radioButton1" IsChecked="True" GroupName="radioButtonGroup" Content="Reminder" HorizontalAlignment="Left" Margin="135,532,0,0" VerticalAlignment="Top"/> <RadioButton x:Name="radioButton2" GroupName="radioButtonGroup" Content="Alarm" HorizontalAlignment="Left" Margin="134,604,0,0" VerticalAlignment="Top"/> <Button Content="Registration" HorizontalAlignment="Left" Margin="328,569,0,0" VerticalAlignment="Top" Click="Button_Click_1"/> </Grid>
[C#]
public partial class Page1 : PhoneApplicationPage { public Page1() { InitializeComponent(); } IEnumerable<ScheduledNotification> notifications; protected override void OnNavigatedTo(NavigationEventArgs e) { ListboxInit(); base.OnNavigatedTo(e); } private void ListboxInit() { //Returns the system all registered notice notifications = ScheduledActionService.GetActions<ScheduledNotification>(); listbox1.ItemsSource = notifications; } //To delete a notice private void deleteButton_Click(object sender, RoutedEventArgs e) { string name = (string)((Button)sender).Tag; ScheduledActionService.Remove(name); ListboxInit(); } //A new notice private void Button_Click_1(object sender, RoutedEventArgs e) { String name = System.Guid.NewGuid().ToString(); if (radioButton1.IsChecked == true) { //Name, Unique Reminder reminder = new Reminder (name); // the message header reminder.Title = textbox1.Text; reminder.Content = "this is to remind the body part. "; //The message type reminder.RecurrenceType = RecurrenceInterval.Daily; //Start time reminder.BeginTime = DateTime.Now + new TimeSpan(0, 0, 30); //The end of time reminder.ExpirationTime = DateTime.Now + new TimeSpan(0, 0, 45); //From the reminder when starting the application startupURI reminder.NavigationUri = new Uri("/Page2.xaml?a=test", UriKind.Relative); //Registration ScheduledActionService.Add(reminder); } else { //Can inform the custom ringtones Alarm alarm = new Alarm(name); alarm.Content = "Here is the alarm clock body part. "; //Remind when playing file alarm.Sound = new Uri("/1.mp3", UriKind.Relative); //The message type alarm.RecurrenceType = RecurrenceInterval.Daily; //Start time alarm.BeginTime = DateTime.Now + new TimeSpan(0, 0, 30); //The end of time alarm.ExpirationTime = DateTime.Now + new TimeSpan(0, 1, 30); //Registration ScheduledActionService.Add(alarm); } ListboxInit(); } }

2)The local Toast

Can be achieved in the Toast message pop up through a local Toast, but when the application runtime does not pop up, so the general plan is invoked in the background. Details see "Windows phone 8 study notes and multi task background agent .


Four, push notification

Push notifications are required by Microsoft push cloud server, because generally speaking, the application after the exit is not retained a background service to wait for news, this practice is electricity. Push notification procedure is, when a message push over, received by the system to unify the completion message, to start the application user selective.

Type 1 push notification

Push notifications are of three main types, as follows:
   The 1 Magnetic notice: News arrived, the default block will update the application, so that direct current application updates.
   2.Toast push notification: News arrived, will hint at the top of the screen pops up a Toast, users click start application.
   3.raw notice: The notice on the premise of application execution, provide flexible message processing, but allows the state will not be able to receive messages.

The realization of the 2 push notification

In order to realize the push notification, first we need to establish a push channel. Establish a push channel in Windows phone, and URI channels. The following code:

[C# Windows phone]
//Magnetic notice private void TileInit() { //Push service channel HttpNotificationChannel pushChannel; //Channel name string channelName = "TileSampleChannel"; InitializeComponent(); //Try to find out whether has been created pushChannel = HttpNotificationChannel.Find(channelName); var newChannel = false; //Not found, A new if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); newChannel = true; } //Notification channel correlationURIWhen the change: pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated); //Error: pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred); if (newChannel) { pushChannel.Open(); //The notification subscriptions to bind to the default block pushChannel.BindToShellTile(); } else { MessageBox.Show(String.Format("ChannelURI: {0}", pushChannel.ChannelUri.ToString())); } } //ToastNotice private void ToastInit() { //Push service channel HttpNotificationChannel pushChannel; //Channel name string channelName = "ToastSampleChannel"; InitializeComponent(); //Try to find out whether has been created pushChannel = HttpNotificationChannel.Find(channelName); var newChannel = false; //Not found, A new if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); newChannel = true; } //Notification channel correlationURIWhen the change: pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated); //Error: pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred); //Receiving Toast message: (if the program does not start the pop-up Toast, otherwise the incident triggered) pushChannel.ShellToastNotificationReceived + = new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived); if (newChannel) { pushChannel.Open(); //The subscription is bound to noticeShellToast pushChannel.BindToShellToast(); } else { MessageBox.Show(String.Format("ChannelURI: {0}", pushChannel.ChannelUri.ToString())); } } //RowNotice private void RawInit() { //Push service channel HttpNotificationChannel pushChannel; //Channel name string channelName = "RawSampleChannel"; InitializeComponent(); //Try to find out whether has been created pushChannel = HttpNotificationChannel.Find(channelName); var newChannel = false; //Not found, A new if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); newChannel = true; } //Notification channel correlationURIWhen the change: pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated); //Error: pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred); //Raw received notification: (only the events that trigger application run time) pushChannel.HttpNotificationReceived + = new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived); if (newChannel) { pushChannel.Open(); //There is no binding operation } else { MessageBox.Show(String.Format("ChannelURI: {0}", pushChannel.ChannelUri.ToString())); } } //URIUpdate void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Dispatcher.BeginInvoke(() => { MessageBox.Show(String.Format("ChannelURI: {0}", e.ChannelUri.ToString())); }); } //When an error is encountered void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e) { //Error processing } //ReceivedToastNotice void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { StringBuilder message = new StringBuilder(); string relativeUri = string.Empty; message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString()); foreach (string key in e.Collection.Keys) { message.AppendFormat("{0}: {1}\n", key, e.Collection[key]); if (key.ToLower() == "wp:param") relativeUri = e.Collection[key]; } Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString())); } //ReceivedRawNotice: void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e) { string message; using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body)) { message = reader.ReadToEnd(); } Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Row {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)) ); }

By pushing the URI, we need a web server, this server is that we used to send their application push message place, if web is.Net, then the implementation is as follows:

[C# .Net]
//The news sent magnet private void SendTile() { try { string subscriptionUri = TextBoxUri.Text.ToString(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri); httpWebRequest.Method = "POST"; string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" + "<wp:Tile>" + "<wp:BackgroundImage>/Assets/Tiles/FlipCycleTileMedium.png</wp:BackgroundImage>" + "<wp:Count>5</wp:Count>" + "<wp:Title>Title</wp:Title>" + "<wp:BackBackgroundImage></wp:BackBackgroundImage>" + "<wp:BackTitle>On the back of the title</wp:BackTitle>" + "<wp:BackContent>Back text content</wp:BackContent>" + "</wp:Tile> " + "</wp:Notification>"; byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage); httpWebRequest.ContentLength = notificationMessage.Length; httpWebRequest.ContentType = "text/xml"; //X-WindowsPhone-TargetSet totoken httpWebRequest.Headers.Add("X-WindowsPhone-Target", "token"); //TileMessage type 1 httpWebRequest.Headers.Add("X-NotificationClass", "1"); using (Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse(); string notificationStatus = response.Headers["X-NotificationStatus"]; string notificationChannelStatus = response.Headers["X-SubscriptionStatus"]; string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"]; } catch (Exception ex) { } } //Send outToastThe news private void SendToast() { try { //ThisURIIs the channel created byWPThe client access to the, To be submitted to the server string uri = TextBoxUri.Text.ToString(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); httpWebRequest.Method = "POST"; string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" + "<wp:Toast>" + "<wp:Text1>Title</wp:Text1>" + "<wp:Text2>Part</wp:Text2>" + "<wp:Param>/Page2.xaml?NavigatedFrom=ToastNotification</wp:Param>" + "</wp:Toast> " + "</wp:Notification>"; byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage); //Set the request header httpWebRequest.ContentLength = notificationMessage.Length; httpWebRequest.ContentType = "text/xml"; //X-WindowsPhone-TargetSet totoast httpWebRequest.Headers.Add("X-WindowsPhone-Target", "toast"); //ToastMessage type 2 httpWebRequest.Headers.Add("X-NotificationClass", "2"); using (Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse(); //To obtain status information of the corresponding head contains string notificationStatus = response.Headers["X-NotificationStatus"]; string notificationChannelStatus = response.Headers["X-SubscriptionStatus"]; string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"]; } catch (Exception ex) { } } //Send outRawThe news private void SendRaw() { try { string subscriptionUri = TextBoxUri.Text.ToString(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri); httpWebRequest.Method = "POST"; //The contents of the message here is entirely custom, Can also be a non XML string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<root>" + "<Value1>a<Value1>" + "<Value2>b<Value2>" + "</root>"; byte[] notificationMessage = Encoding.Default.GetBytes(rawMessage); httpWebRequest.ContentLength = notificationMessage.Length; httpWebRequest.ContentType = "text/xml"; //No X-WindowsPhone-Target //Raw message type is 3 httpWebRequest.Headers.Add("X-NotificationClass", "3"); using (Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse(); string notificationStatus = response.Headers["X-NotificationStatus"]; string notificationChannelStatus = response.Headers["X-SubscriptionStatus"]; string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"]; } catch (Exception ex) { } }

Author: [Lipan]
Source: []
Copyright statement: the copyright belongs to the author CO and garden blog. Reproduced must indicate the original source and the author, and keep the original point to the link, must not change the content of the original. Otherwise, the author will retain the legal responsibility.
A: start the series of directory Windows phone 8 study notes application next: Windows phone 8 multi task learning notes
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Milly at November 25, 2013 - 4:21 AM