2015-02-23 63 views
0

注意:我只使用模擬器測試過,並使用內置功能推送敬酒。我假設這不是一個模擬器問題。如何僅在應用程序處於前景時抑制推送Toast通知?

我跟着this guide爲了在應用程序運行時攔截推送敬酒通知。但是,我只想在應用程序處於前臺時抑制敬酒通知。當另一個應用程序處於前臺時它仍應該顯示。所以我寫了下面的處理程序App.xaml.cs(並訂閱了PushNotificationReceived事件):

private async void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e) 
    { 
     string msg = ""; 
     if (e.NotificationType == PushNotificationType.Toast) 
     { 
      await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
       { 
        if (Window.Current.Visible) 
        { 
         msg += " Toast canceled."; 
         e.ToastNotification.SuppressPopup = true; 
        } 
       }); 

      if (true) // actually determines if it's a certain type of toast 
      { 
       await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => 
        { 
         ConfirmationContentDialog confirmationDialog = new ConfirmationContentDialog(); 
         confirmationDialog.SetMessage("Please confirm that you like turtles." + msg); 
         await confirmationDialog.ShowAsync(); 
        }); 
      } 
     } 
    } 

所以這部作品,在這個意義上,我只看到了「舉杯取消」的消息時,應用程序是在前臺接收時推送通知。當我在開始屏幕或其他地方時,我總是得到祝酒。這很好。但是,當應用程序處於前臺時,有時(通常是在發送第二次推送之後),敬酒人員仍會顯示(即使顯示「取消Toast」)。但有時它不會。這是相當不一致的。

這讓我相信,由於等待,有時候,在代碼在UI線程上運行之前,有時敬酒會通過,以檢查應用程序是否可見。但是,我不能使用調度程序從這裏訪問Window.Current.Visible。我甚至試過CoreApplication.MainView.CoreWindow.Visible,但是這給了我「爲不同的線程編組的接口」異常。說到這一點,我不明白CoreApplication.MainView.CoreWindow.Dispatcher可以從任何地方調用,但不是CoreApplication.MainView.CoreWindow.Visible?這甚至如何工作。

無論如何,我該如何解決這個問題?我想保留在App.xaml.cs之內,因爲我在這個應用程序中有許多頁面,但是無論用戶在哪個頁面上,都無需顯示此內容對話框,也無需將用戶重定向到其他頁面。不過,我當然願意提出新的建議。

+1

這實際上可能是一個仿真器/ Visual Studio問題,因爲:除非您實際上在Visual Studio中推送掛起按鈕,否則在連接調試器時,應用程序不會*掛起*。這可能會導致您的行爲不一致。 – 2015-02-24 09:08:50

+1

其他想法可能是:嘗試檢查*懸浮*事件,切換顯示吐司切換或不切換? – 2015-02-24 09:11:00

+1

是的:使用** async void **意味着它是* fire and forget *因此推送通知處理不會等待它,並且SuppressPopup只有在處理通知後纔可能設置。 – 2015-02-24 09:12:33

回答

0

我解決了這個問題按啓Brummund的建議通過使用App類的簡單布爾切換,並訂閱了VisibilityChanged事件,像這樣:

private bool APP_VISIBLE = true; 

protected override async void OnLaunched(LaunchActivatedEventArgs e) 
{ 
    // Stuff put here by Visual Studio 

    Window.Current.VisibilityChanged += OnVisibilityChanged; 

    Window.Current.Activate(); 
} 

private void OnVisibilityChanged(object sender, VisibilityChangedEventArgs e) 
{ 
    if (e.Visible) 
     APP_VISIBLE = true; 
    else 
     APP_VISIBLE = false; 
} 

這樣我可以用APP_VISIBLE壓制彈出無必須立即使用調度員和吐司。

相關問題