如何在WP8中关闭win应用程序时Toast通知

本文关键字:应用程序 win Toast 通知 WP8 | 更新日期: 2023-09-27 18:13:22

我想实现Toast和Tile通知。我的通知必须满足一些标准,比如它需要能够在我的应用程序关闭时运行。例如,当应用程序关闭时,生日提醒可以在后台运行。

示例我发现:

ShellToast toast = new ShellToast();
toast.Title = "Toast Title: ";
toast.Content = "TEST";
toast.Show();

上面的例子在应用程序运行时起作用。下面是我的代码:

    private void StartPeriodicAgent()
    {
        // Variable for tracking enabled status of background agents for this app.
        agentsAreEnabled = true;
        // Obtain a reference to the period task, if one exists
        periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
        // If the task already exists and background agents are enabled for the
        // application, you must remove the task and then add it again to update 
        // the schedule
        if (periodicTask != null)
        {
            RemoveAgent(periodicTaskName);
        }
        periodicTask = new PeriodicTask(periodicTaskName);
        periodicTask.ExpirationTime = System.DateTime.Now.AddDays(1);
        // The description is required for periodic agents. This is the string that the user
        // will see in the background services Settings page on the device.
        periodicTask.Description = "This demonstrates a periodic task.";
        // Place the call to Add in a try block in case the user has disabled agents.
        ScheduledActionService.Add(periodicTask);
    }
  private void RunBackgroundWorker()
    {
        //PhoneCallTask calltask = new PhoneCallTask();
        //calltask.PhoneNumber = "03336329631";
        //calltask.DisplayName = "arslan";
        //calltask.Show();

        BackgroundWorker backroungWorker = new BackgroundWorker();
        backroungWorker.DoWork += ((s, args) =>
        {
            Thread.Sleep(10000);
        });
        backroungWorker.RunWorkerCompleted += ((s, args) =>
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                var toast = new ToastPrompt
                {
                    Title = "Simple usage",
                    Message = "Message"
                };
                toast.Show();


            }
        );
        });
        backroungWorker.RunWorkerAsync();
    }

但是我没有收到任何通知。谁能告诉我如何设置通知工作时,应用程序不运行?

如何在WP8中关闭win应用程序时Toast通知

BackgroundWorker不同于定期运行的计划任务。

添加Windows Phone计划任务代理,并在该项目中编写代码逻辑来调用生成toast所需的调用。

protected override void OnInvoke(ScheduledTask task)
{
  ------------------------------------------------
  Your code for scheduled task running.
} 

一旦你的代码已经完成,你可以调用NotifyComplete()来指示计划任务的工作何时结束。

backgroundworker只是在一个单独的线程中运行你的代码,与计划任务没有关系,除了事实;你可以在计划任务中使用后台线程。

为了让你的逻辑在主应用程序和计划任务之间共享:-创建一个单独的项目,并在其中放入可重用/共享的代码。在主应用程序和计划任务中引用它来共享/访问变量。

在单独的项目中使用IsolatedStorageFile和Mutex,并在两者之间共享DLL

* Schedule任务的随机引用示例:http://wildermuth.com/2011/9/6/Periodic_Agents_on_Windows_Phone_7_1*