2015-08-21 20 views
2

即使在應用程序未運行時收到推送通知,我也想執行自己的功能。用戶不需要點擊操作欄中的通知。在Window Phone 8.1從服務器接收到原始推送通知後執行某些功能

BackgroundTask.cs我有下面的代碼片段:

namespace BackgroundTasks 
{ 
public sealed class SampleBackgroundTask : IBackgroundTask 
{ 
    public void Run(IBackgroundTaskInstance taskInstance) 
    { 
     ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; 
     string taskName = taskInstance.Task.Name; 
     Debug.WriteLine("Background " + taskName + " starting..."); 

     RawNotification notification = (RawNotification)taskInstance.TriggerDetails; 
     settings.Values[taskName] = notification.Content; 

     Debug.WriteLine("Background " + taskName + " completed!"); 
    } 
} 
} 

這是我的代碼以PushNotificationTrigger註冊後臺任務:

private async void RegisterBackgroundTask() 
    { 

     BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); 
     PushNotificationTrigger trigger = new PushNotificationTrigger(); 


     taskBuilder.SetTrigger(trigger); 

     taskBuilder.TaskEntryPoint = "BackgroundTasks.SampleBackgroundTask"; 
     taskBuilder.Name = "SampleBackgroundTask"; 

     try 
     { 
      BackgroundTaskRegistration task = taskBuilder.Register(); 
     } 
     catch (Exception ex) 
     { 
     } 
    } 

enter image description here

我設置了所有必要的Package.appmanifest之後RegisterBackgroundTask被執行後,假設BackgroundTask必須註冊。但在我的情況下,我沒有找到任何BackgroundTask註冊:

enter image description here

以下是代碼片段,以獲得Channel Uri

private async void OpenChannelAndRegisterTask() 
    { 
     try 
     { 
      PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); 
      string uri = channel.Uri; 
      RegisterBackgroundTask(); 
     } 
     catch (Exception ex) 
     { 
     } 
    } 

而且從webserivce我送原像的通知這樣的:

namespace SendToast 
{ 

public partial class SendToast : System.Web.UI.Page 
{ 
    private string sid = "PACKAGE SID"; 
    private string secret = "CLIENT SECRET"; 
    private string accessToken = ""; 

    [DataContract] 
    public class OAuthToken 
    { 
     [DataMember(Name = "access_token")] 
     public string AccessToken { get; set; } 
     [DataMember(Name = "token_type")] 
     public string TokenType { get; set; } 
    } 

    OAuthToken GetOAuthTokenFromJson(string jsonString) 
    { 
     using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) 
     { 
      var ser = new DataContractJsonSerializer(typeof(OAuthToken)); 
      var oAuthToken = (OAuthToken)ser.ReadObject(ms); 
      return oAuthToken; 
     } 
    } 

    public void getAccessToken() 
    { 
     var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.sid)); 
     var urlEncodedSecret = HttpUtility.UrlEncode(this.secret); 

     var body = 
      String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret); 

     var client = new WebClient(); 
     client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 

     string response = client.UploadString("https://login.live.com/accesstoken.srf", body); 
     var oAuthToken = GetOAuthTokenFromJson(response); 
     this.accessToken = oAuthToken.AccessToken; 
    } 

    protected string PostToCloud(string uri, string xml, string type = "wns/raw") 
    { 
     try 
     { 
      if (accessToken == "") 
      { 
       getAccessToken(); 
      } 
      byte[] contentInBytes = Encoding.UTF8.GetBytes(xml); 

      WebRequest webRequest = HttpWebRequest.Create(uri); 
      HttpWebRequest request = webRequest as HttpWebRequest; 
      webRequest.Method = "POST"; 

      webRequest.Headers.Add("X-WNS-Type", type); 
      webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken)); 

      Stream requestStream = webRequest.GetRequestStream(); 
      requestStream.Write(contentInBytes, 0, contentInBytes.Length); 
      requestStream.Close(); 

      HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); 

      return webResponse.StatusCode.ToString(); 
     } 
     catch (WebException webException) 
     { 
      string exceptionDetails = webException.Response.Headers["WWW-Authenticate"]; 
      if ((exceptionDetails != null) && exceptionDetails.Contains("Token expired")) 
      { 
       getAccessToken(); 
       return PostToCloud(uri, xml, type); 
      } 
      else 
      { 
       return "EXCEPTION: " + webException.Message; 
      } 
     } 
     catch (Exception ex) 
     { 
      return "EXCEPTION: " + ex.Message; 
     } 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     string channelUri = "https://hk2.notify.windows.com/?token=AwYAAAAL4AOsTjp3WNFjxNFsXmFPtT5eCknoCeZmZjE9ft90H2o7xCOYVYZo7o10IAl6BpK9wTxpgIKIeF0TGF2GJZhWAExYd7qEAIlJQNvApQ3V7SA36%2brEow%2bN3NwVDGz4UI%3d"; 

     if (Application["channelUri"] != null) 
     { 
      Application["channelUri"] = channelUri; 
     } 
     else 
     { 
      Application.Add("channelUri", channelUri); 
     } 

     if (Application["channelUri"] != null) 
     { 
      string aStrReq = Application["channelUri"] as string; 
      string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
      "<root>" + 
       "<Value1>" + "Hello" + "<Value1>" + 
       "<Value2>" + "Raw" + "<Value2>" + 
      "</root>"; 
      Response.Write("Result: " + PostToCloud(aStrReq, rawMessage)); 
     } 
     else 
     { 
      Response.Write("Application 'channelUri=' has not been set yet"); 
     } 
     Response.End(); 
    } 
} 
} 

我只是想引起我的BackgroundTask當原通知接收地即使應用程序沒有運行時也是如此。請幫幫我。提前致謝。

回答

2

嘗試使用原始通知觸發後臺任務。您必須使用PushNotificationTrigger註冊您的後臺任務。這裏是Documentation鏈接。

+0

感謝您的回答。我們必須處理爲channel.PushNotificationReceived + = PushNotificationReceived; ?? –

+0

您需要創建一個實現IBackgroundTask的密封SmplBackgroundTask。然後創建一個BackgroundTaskBuilder的對象,併爲該創建的SmplBackgroundTask指定該BackGroundTaskBuilder的TaskEntry點的值。之後,分配PushNotificationTrigger。 以下是https://code.msdn.microsoft.com/windowsapps/Raw-notifications-sample-3bc28c5d#content – ssakash

+0

中的代碼示例。請參閱編輯後的版本。我編輯了問題。我已經像你說的那樣做了,但是我的後臺任務沒有註冊。 –

相關問題