Um toast Ai?? exibido no topo da tela para notificar o usuA?rio de algum ecento, como uma mensagem, um news ou um alerta de mudanAi??a climA?tica, por exemplo.
Funcionamento da Toast Notification
A toast notification Ai?? exibida por cerca de 10 segundos. O usuA?rio pode deslizA?-la para a direita se ele quer removA?-la de imediato. Se a toast notification Ai?? tocada, por padrA?o, a pA?gina principal da aplicaAi??A?o serA? aberta, mas o desenvolvedor pode configurar para que uma pA?gina alternativa seja aberta. A toast sA? serA? mostrada se a aplicaAi??A?o estiver rodando em background.
Propriedades da Toast
A cor de fundo da toas Ai?? a cor do temaAi??selecionado pelo usuA?rio nas configuraAi??Ai??es do telefone. As outras propriedades da toast podem ser vistas na imagem abaixo.
Criando uma Toast Notification utilizando cA?digo
using Microsoft.Phone.Shell; // Instantiation of a toast notification. ShellToast toast = new ShellToast(); // Definition of the toast title. toast.Title = "INdT FRAMEWORK"; // Definition of the toast message. toast.Content = "See current longitude."; // Definition of the URI to navigate to if the user taps the toast message. // If the URI to navigate isn't defined then the default URI is the URI // of the navigation page of the application. toast.NavigationUri = new Uri("/SecondPage.xaml", UriKind.Relative); // Command that displays the toast notification to the user. toast.Show();
Criando um exemplo com Toast Notification
Este Ai?? um exemplo de uma aplicaAi??A?o que segueAi??sua localizaAi??A?o e roda em background..
Habilitando uma app que segue alguma localizaAi??A?o a rodar em background
1. Crie uma nova App para Windows Phone e adicione a capabilidade ID_CAP_LOCATION no arquivoAi??WMAppManifest.xml.
How much zanaflex can i take
2. Habilite a app a rodar em background modificando o arquivo de manifesto. Para essa tarefa, clique com o botA?o direito no arquivoAi??WMAppManifest.xmlAi??Ai??e selecioneAi??View Code. Depois disso, substitua o elemento DefaultTask element com o cA?digo abaixo:
<DefaultTask Name="_default" NavigationPage="MainPage.xaml"> <BackgroundExecution> <ExecutionType Name="LocationTracking"/> </BackgroundExecution> </DefaultTask>
3. Registre o eventoAi??RunningInBackgroundAi??no arquivoAi??App.xaml. ele serA? chamado quando a aplicaAi??A?o for para segundo plano e irA? habilitar vocA? a identificar quando a aplicaAi??A?o estA? em primeiro ou segundo plano.
<Application.ApplicationLifetimeObjects> <shell:PhoneApplicationService Launching="Application_Launching" Closing="Application_Closing" Activated="Application_Activated" Deactivated="Application_Deactivated" RunningInBackground="Application_RunningInBackground"/> </Application.ApplicationLifetimeObjects>
4. No arquivoAi??App.xaml.cs, declare o objetoAi??Geolocation, Que serA? o responsA?vel em obter as coordenadas atuais do device, alAi??m da variA?vel boleanaAi??IsRunningInBackground, que serA? usada para verificar se a App estA? em primeiro ou segundo plano. Ai??Depois disso, passe a instA?ncia do objeto Geolocation para o construtor da classe App.
Vale a pena notar que o Geolocation Ai?? um objeto da classe Geolocation, que estA? no namespace INdTFramework.Maps; Rodar em segundo plano usando o tracking de localizaAi??A?o somente ocorre se alguma classe que consome coordenadas Ai??geogrA?ficas do device Ai?? utilizada.Ai??
using INdTFramework.Maps; public partial class App : Application { // Other declarations of the App class. // Property to check whether the execution occurs in the foreground or background. public static bool IsRunningInBackground { get; set; } // Object that will get the current geographical position of the device. public static Geolocation Geolocation { get; set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Other commands of constructor stay here. // Instantiation of the Geolocation object. Geolocation = new Geolocation(); } // Other commands of the App class. }
5. No arquivo App.xaml.cs, adicione oAi??event handlerAi??RunningInBackground. Esse evento Ai?? chamado quando o usuA?rio sai da App enquanto a sua location estA? ativamente sendo “trackeada” e sua App entre em segundo plano. Quando esse evento Ai?? chamado, a variA?vel global IsRunningInBackground global recebe o valorAi??true.
// Code to execute when the application starts the execution in background. // This code will not execute when the application is in background. private void Application_RunningInBackground(object sender, RunningInBackgroundEventArgs e) { IsRunningInBackground = true; }
6. No arquivoAi??App.xaml.cs, atualize o mAi??todoAi??Application_ActivatedAi??para a variA?vel global IsRunningInBackground receber o valorAi??false. Se a app estA? rodando em segundo plano e o usuA?rio ativa a App, por exemplo, tocando no tile da App, esse mAi??todo que Ai?? o handler do evento Activated Buy minocycline hcl Nombre comercial y generico del cytotec Ai??Ai?? chamado.
// Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { IsRunningInBackground = false; }
7. Isto feito, a idAi??ia do nosso exemplo consiste em exibir as coordenadas atuais do device.Se a App Ai?? colocada em Background, uma toast notifcation vai aparecer. Se antes da app ir para segundo plano o usuA?rio estava vendo sua latitude corrente, a toast notification vai mostrar a mensagem Ai??”See current latitude.”; quando o usuA?rio tocar na toast, ele serA? levado para a pA?gina que mostra a latitude atual do device.Mas se ele estava vendo sua longitude, a mensagem mostrada Ai?? “See current longitude.” E o usuA?rio serA? levado para a page que mostra a sua longitude.
Portanto, quando a pA?gina principal estA? carregada, o cA?digo abaixo Ai?? executado, e um timer comeAi??a a contar 5 segundos. EntA?o a cada 5 segundos as coordenadas sA?o checadas se sA?o vA?lidas. Caso elas existam, a latitude Ai?? exibida. Se a aplicaAi??A?ofor para segundo plano, a toast serA? mostrada. O mesmo processo ocorre se a segunda pA?gina Ai?? carregada, mas nesse caso Ai?? a longitude que Ai?? exibida.
MainPage.xaml:
<phone:PhoneApplicationPage x:Class="ToastNotificationSample.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True" Loaded="MainPage_Loaded"> <Grid x:Name="LayoutRoot" Background="Black"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock Text="INdT FRAMEWORK" Style="{StaticResource PhoneTextNormalStyle}" Foreground="White"/> <TextBlock Text="latitude" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Foreground="White"/> </StackPanel> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Name="Latitude" Text="Loading latitude..." FontSize="30" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> </Grid> <phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar ForegroundColor="White" BackgroundColor="Black"> <shell:ApplicationBarIconButton x:Name="btnLongitude" Text="longitude" IconUri="/Assets/AppBar/next.png" Click="btnLongitude_Click"/> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> </phone:PhoneApplicationPage>
MainPage.xaml.cs:
using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using System; using System.Windows; using System.Windows.Threading; namespace ToastNotificationSample { public partial class MainPage : PhoneApplicationPage { // Timer. DispatcherTimer timer; public MainPage() { InitializeComponent(); } private void MainPage_Loaded(object sender, RoutedEventArgs e) { // Instantiation of the timer. // It's created to check whether object 'App.Geolocation' already obtained valid // coordinates of the user. // In addition, every 5 seconds one toast notification will be displayed if the // application is running in background. timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 5); timer.Tick += timer_Tick; timer.Start(); } private void timer_Tick(object sender, EventArgs e) { if (App.Geolocation.IsFinished) { if (App.Geolocation.Status != System.Device.Location.GeoPositionStatus.Disabled && App.Geolocation.Status != System.Device.Location.GeoPositionStatus.NoData) { // If the coordinates of the user were obtained successfully, // the latitude is displayed to the user. Latitude.Text = App.Geolocation.Latitude.ToString(); } } string currentSource = ((PhoneApplicationFrame)Application.Current.RootVisual).CurrentSource.ToString(); // If the application is running in background and the last page before going to the // background was the MainPage.xaml page, the toast notification is displayed // to the user. if (App.IsRunningInBackground && currentSource == "/MainPage.xaml") { // Function to display the toast notification. ShowToast(); } } private void ShowToast() { // Instantiation of a toast notification. // The toast notification will not be displayed if the application is running // in foreground. ShellToast toast = new ShellToast(); // Definition of the toast title. toast.Title = "INdT FRAMEWORK"; // Definition of the toast message. toast.Content = "See current latitude."; // Command that displays the toast notification to the user. // As it was not defined the URI to navigate then the default URI is the URI // of the navigation page of the application. toast.Show(); } private void btnLongitude_Click(object sender, EventArgs e) { // Go to second page. NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative)); } } }
O cA?digo fonte e outros A?timos exemplos estA?o disponAi??veis para download no CodePlex.