2017-04-07 1 views
0

Raw Pushnotification 트리거에 의해 트리거되는 백그라운드 작업이있는 Windows 10 UWP 앱을 개발하려고합니다. 테스트에서 Raw 알림이 실제로 제대로 작동하는지 확인하기 위해 앱에 핸들러가 있습니다. 여기에 코드 조각은 다음과 같습니다UWP PushNotificationTrigger가 백그라운드 작업을 트리거하지 않습니다.

다음
PushNotificationChannel _channel = null; 

    private async void AppInit() 
    { 
     _channel = await Common.WNSHelper.GetChannelAsync(); 
     if (_channel != null) 
     { 
      _channel.PushNotificationReceived += _channel_PushNotificationReceived; 
     } 
     await InstallPositionBackgroundTask(); 
     } 

    private async void _channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) 
    { 
     if (args.NotificationType == PushNotificationType.Raw) 
     { 
      Common.GeneralHelper.SendToast("At App PositionBackgroundTask"); 
     } 
    } 

    private async Task InstallPositionBackgroundTask() 
    { 
     var taskName = "PositionBackgroundTask"; 

     foreach (var tsk in BackgroundTaskRegistration.AllTasks) 
     { 
      if (tsk.Value.Name == taskName) 
      { 
       tsk.Value.Unregister(true); 
      } 
     } 

     var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; 
     if (cost == BackgroundWorkCostValue.High) 
     { 
      return; 
     } 

     var allowed = await BackgroundExecutionManager.RequestAccessAsync(); 
     if (allowed == BackgroundAccessStatus.AllowedSubjectToSystemPolicy 
      || allowed == BackgroundAccessStatus.AlwaysAllowed) 
     { 
      var builder = new BackgroundTaskBuilder(); 

      builder.Name = nameof(PositionBackgroundTask.PositionBackgroundTask); 
      builder.CancelOnConditionLoss = false; 
      builder.TaskEntryPoint = typeof(PositionBackgroundTask.PositionBackgroundTask).FullName; 
      builder.SetTrigger(new PushNotificationTrigger()); 
      BackgroundTaskRegistration task = builder.Register(); 
      task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); 

      Common.GeneralHelper.SendToast("Position Task Installed. " + System.DateTime.Now.ToString()); 
     } 
    } 
    private async void button_Click(object sender, RoutedEventArgs e) 
    { 
     // send it 
     var response = await Common.WNSHelper.PushRawAsync<Common.RawRequest>(_channel.Uri, new RawRequest() { RequestType = RawRequestType.RequestPosition, FromDeviceId = _allDevices[0].D_Id }, null); 
    } 

다음은 백그라운드 작업

namespace PositionBackgroundTask 

{ 
    public sealed class PositionBackgroundTask 
    { 

     BackgroundTaskDeferral _deferral; 
     public async void Run(IBackgroundTaskInstance taskInstance) 
     { 
      Common.GeneralHelper.SendToast("At PositionBackgroundTask"); 

      var cancel = new System.Threading.CancellationTokenSource(); 
      taskInstance.Canceled += (s, e) => 
      { 
       cancel.Cancel(); 
       cancel.Dispose(); 
      }; 

      _deferral = taskInstance.GetDeferral(); 
      try 
      { 
       RawNotification notification = (RawNotification)taskInstance.TriggerDetails; 
       //: 
       //: 
       //: 
      } 
      finally 
      { 
       _deferral.Complete(); 
      } 
     } 
    } 
} 

의 다음 매니페스트

<Extension Category="windows.backgroundTasks" EntryPoint="PositionBackgroundTask.PositionBackgroundTask"> 
    <BackgroundTasks> 
    <Task Type="pushNotification" /> 
    </BackgroundTasks> 
</Extension> 

있어 원시 통지

public static async Task<HttpResponseMessage> PushRawAsync<T>(string channelUri, RawRequest request, T rawData) 
{ 
    // Get App authorization 
    string appDataSecret = MYAPPSECRET; 
    Uri requestUri = new Uri(@"https://login.live.com/accesstoken.srf"); 

    var client = new System.Net.Http.HttpClient(); 
    System.Net.Http.HttpResponseMessage response = await client.PostAsync(requestUri, new StringContent(appDataSecret, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded")); 
    string responJsonText = await response.Content.ReadAsStringAsync(); 

    WMNToken token = JsonConvert.DeserializeObject<WMNToken>(responJsonText); 

    string requestStr = JsonConvert.SerializeObject(request) + ";" + JsonConvert.SerializeObject(rawData); 
    var content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(requestStr))); 

    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token.Token_type, token.Access_token); 
    client.DefaultRequestHeaders.Add("X-WNS-Type", "wns/raw"); 

    response = await client.PostAsync(channelUri, content); 
    return response; 
} 

를 보낼 수있는 코드이다 앱 정의 y는 알림을 받았지만 백그라운드 작업은 절대로받지 못했습니다. 나는 무엇을 잘못 했는가?

추가 정보 : 푸시 알림 상자를 치고 있지만 경우에이 오류가

Activation of the app 45737MyName.TestPushNotificationpartofemail_4rhf8erfmecqa!App for the Windows.BackgroundTasks contract failed with error: No such interface supported. 

를 기록 얻었다처럼 외모와 내가이

처럼해야 IBackgroundTask 를 서브 클래 싱하지 않았다 밝혀
public sealed class PositionBackgroundTask : IBackgroundTask 
+0

알림없이 백그라운드 작업을 실행할 수 있습니까? 즉, 코드/단추 클릭을 사용하여 수동으로 트리거 할 수 있습니까? – Laith

+0

내가 읽은 것에서는 푸시 알림을 Visual Studio 내에서 트리거 할 수 없습니다. 실제로 TimeTrigger 이벤트 백그라운드 작업이 있고 Visual Studio 내에서 테스트 할 수있었습니다. 푸시 알림 백그라운드 작업을 실제로 실행하는 방법이 있습니까? – dreamfly

+0

백그라운드 작업 코드가 대체 트리거로 트리거되는 것을 보았습니까? – Laith

답변

0

배경 작업 IBackgroundTask

공공 봉인 클래스 위치의 서브 클래스해야 BackgroundTask : IBackgroundTask

관련 문제