运行收到短信后的新后台事件
移动宽带短信平台为接收的新短信数据提供单独的系统事件,具体取决于它是来自移动网络运营商的管理短信通知还是常规短信。 从移动网络运营商接收的新管理短信通知的后台系统事件只能由移动宽带应用访问。
应用必须已收到用户同意,才能使用短信在后台任务中读取新收到的短信。 如果应用是第一次访问短信,则无法从后台任务读取新收到的短信的内容,因为应用无法从后台任务触发系统短信设备同意提示。
以下代码示例演示了一个后台任务,该任务设计为在收到新短信时运行。
C# 后台任务代码
namespace SmsBackgroundSample
{
public sealed class SmsBackgroundTask : IBackgroundTask
{
// The Run method is the entry point of a background task.
public void Run(IBackgroundTaskInstance taskInstance)
{
// Associate a cancellation handler with the background task.
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
ManualResetEvent manualEventWaiter = new ManualResetEvent(false);
manualEventWaiter.Reset();
// Do the background task activity.
DisplayToastAsync(taskInstance, manualEventWaiter);
// Wait until the async operation is done. We need to do this else the background process will exit.
manualEventWaiter.WaitOne(5000);
Debug.Print("Background " + taskInstance.Task.Name + (" process ran"));
}
async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)
{
SmsReceivedEventDetails smsDetails = (SmsReceivedEventDetails)taskInstance.TriggerDetails;
SmsBinaryMessage smsEncodedmsg = (SmsBinaryMessage) smsDetails.BinaryMessageMessage;
SmsTextMessage smsTextMessage = Windows.Devices.Sms.SmsTextMessage.FromBinaryMessage(smsEncodedmsg);
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements.Item(0).AppendChild(toastXml.CreateTextNode(smsTextMessage.From));
stringElements.Item(1).AppendChild(toastXml.CreateTextNode(smsTextMessage.Body));
ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);
manualEventWaiter.Set();
}
}
用于注册后台任务的 JavaScript 应用代码
var triggerAway = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.smsReceived, false);
var builderAway = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
builderAway.setTrigger(triggerAway);
builderAway.taskEntryPoint = "HelloWorldBackground.BackgroundTask1";
builderAway.name = "Sms";
var taskAway = builderAway.register();
taskAway.addEventListener("progress", new ProgressHandler(taskAway).onProgress);
taskAway.addEventListener("completed", new CompleteHandler(taskAway).onCompleted);