当应用程序在wp8中的前台运行时,如何获取Toast通知

时间:2016-04-28 13:27:38

标签: windows-phone-8 phonegap-pushplugin

我想实施" toast"我的Windows手机应用程序内的通知。我正在实施推送消息,但我希望它们始终显示。无论应用程序是否正在运行。推送通知将在应用程序关闭时处理它,但不会在它运行时处理。此外,如果我手动创建一个shelltoast,它将无法显示。为了使它变得更加困难,我无法使用任何外部dll。我只想使用代码。最好的方法是什么?我已经知道了ToastNotificationRecieved事件。我想知道如何实现它,以便它显示一个"吐司"喜欢不使用框架的消息

我的代码在

下面

PushPlugin.cs(c#code)

public void showToastNotification(string options)
    {

        ShellToast toast;
        if (!TryDeserializeOptions(options, out toast))
        {
            this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            return;
        }
        Deployment.Current.Dispatcher.BeginInvoke(toast.Show);

    }



public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
 var toast = new PushNotification
            {
                Type = "toast"
            };

            foreach (var item in e.Collection)
            {
                toast.JsonContent.Add(item.Key, item.Value);
            }

            this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
        }

在javascript中

function onNotificationWP8(data) {
    var pushNotification;
    pushNotification = window.plugins.pushNotification;
    pushNotification.showToastNotification(successHandler, errorHandler,
      {
          "Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
      });

}

2 个答案:

答案 0 :(得分:0)

在没有Windows Phone 8 Update 3的设备上,当目标应用程序在前台运行时,不会显示Toast通知。在具有Windows Phone 8 Update 3的设备上,当目标应用程序在前台运行时会显示Toast通知,但会被其他活动(如电话或锁定屏幕)遮挡。

以下C#代码示例显示了使用本地代码创建Toast通知的属性。

// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();

thread让你只需要

答案 1 :(得分:0)

public static class Notification
{
    public static string ChannelURI = string.Empty;

    public static void MainNotificationCallFunction()
    {
        try
        {
            NotificationMessage("Test Notification");
        }
        catch (Exception e)
        { }
    }

    public static void NotificationMessage(string Message)
    {
        try
        {
            ToastTemplateType toastType = ToastTemplateType.ToastText02;

            XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
            XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
            toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
            IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
            ((XmlElement)toastNodeJob).SetAttribute("duration", "long");
            ToastNotification toastJob = new ToastNotification(toastXmlJob);
            ToastNotificationManager.CreateToastNotifier().Show(toastJob);
        }
        catch (Exception e)
        { }
    }

    public static void PushNotification()
    {
        try
        {
            /// Holds the push channel that is created or found.
            HttpNotificationChannel pushChannel;
            string channelName = "Usman's Channel";

            // Try to find the push channel.
            pushChannel = HttpNotificationChannel.Find(channelName);

            // If the channel was not found, then create a new connection to the push service.
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                //// Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);

                pushChannel.Open();
                pushChannel.BindToShellTile();
                pushChannel.BindToShellToast();
            }
            else
            {
                //// The channel was already open, so just register for all the events.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
            }
        }
        catch (Exception ex)
        { }
    }
    private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
    {
        try
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
                MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));

            });
        }
        catch (Exception ex)
        { }
    }
    private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
    {
        try
        {
            // Error handling logic for your particular application would be here.
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
        }
        catch (Exception ex)
        { }
    }
    private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
    {
        try
        {
            string message;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
            {
                message = reader.ReadToEnd();
            }

            Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
        }
        catch (Exception ex)
        { }
    }

    private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
    {
        try
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
            });
        }
        catch (Exception ex)
        { }
    }
    private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
    {
        try
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                //ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
                MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
            });
        }
        catch (Exception ex)
        { }
    }
    private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
    {
        try
        {
            StringBuilder message = new StringBuilder();
            string relativeUri = string.Empty;

            message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());

            using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
            {
                message.AppendFormat(reader.ReadToEnd());
            }

            // Display a dialog of all the fields in the toast.
            Deployment.Current.Dispatcher.BeginInvoke(() => 
            {
                MessageBox.Show(message.ToString());
            });
        }
        catch (Exception ex)
        { }
    }
}