Toast notification when app in background in Windows phone 8.1
我想在我的应用程序处于后台时向行动中心发送敬酒通知。因此,我设置了一个计时器,当我从应用程序启动计时器时,在10秒钟后它会产生吐司通知。现在,当我在调试器中尝试使用它时,即使按了主屏幕按钮或使用调试器暂挂选项挂起了应用程序,也会产生吐司。但是,当我部署该应用程序时,启动计时器并单击"主页"按钮时,它不会产生吐司。任何人都可以为此提出建议的解决方案吗?
添加代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | private Timer stateTimer; private void Button_Click(object sender, RoutedEventArgs e) { TimerCallback timerDelegate = new TimerCallback(timer_Tick); TimeSpan delayTime = new TimeSpan(0, 0, 10); AutoResetEvent autoEvent = new AutoResetEvent(false); TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 0); Timer notification_timer = new Timer(timerDelegate, autoEvent, delayTime, intervalTime); } private void timer_Tick(object state) { ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode("Download has complete")); toastTextElements[1].AppendChild(toastXml.CreateTextNode("Download has complete")); IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); ((XmlElement)toastNode).SetAttribute("duration","long"); ((XmlElement)toastNode).SetAttribute("launch","{"type":"toast","param1":"12345","param2":"67890"}"); ToastNotification toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } |
调试时,除非从Visual Studio的生命周期事件中明确选择暂停,否则您的应用程序永远不会暂停。因此,当您按下主屏幕按钮时,您的应用程序实际上将继续运行。
在实际设备上运行没有附加调试器的应用程序时,情况并非如此。按下主屏幕按钮后,您的应用将被暂停,直到恢复后才能运行。
您必须使用后台任务在后台执行代码。