当Windows 8 metro应用程序启动时,LaunchUriAsync与自定义方案

时间:2014-01-15 13:11:34

标签: c# windows-8 microsoft-metro uri

当我的应用程序以此代码开头时,我尝试LaunchUriAsync:

/// <summary>
/// Navigate to the given URI in a web browser task if the uri is valid
/// We can use all scheme provide by windows excepted file:///
/// </summary>
/// <param name="uri">Uri of the page</param>
public async void TryNavigateToBrowser(string uri)
{
  if (uri != null && uri != "")
  {
    try
    {
      /* Firstly we try to made a launch async for custom URI scheme */
      var success = await Windows.System.Launcher.LaunchUriAsync(new Uri(uri));

      /* Secondly if it doesn't works we try the same but in UI thread
       * If a custom scheme is tried to be displayed in UI thread UI should crash */
      if (!success)
      {
        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
          /* we made a synchronous call to LaunchUriAsync in UI thread */
          var successUI = Windows.System.Launcher.LaunchUriAsync(new Uri(uri)).AsTask().Result;

          if (!successUI)
          {
            TryNavigateToBrowser(uri);
          }
        });
      }
    }
    catch (Exception)
    {
      /* If URI isn't well formated we try to found a file to launch it */
      NavigateToLocalUri(uri);
    }
  }
}

/// <summary>
/// Use to provide customer sended URI for opening file in app storage
/// </summary>
/// <param name="uri"></param>
internal static async void NavigateToLocalUri(string uri)
{
  try
  {
    StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(uri);
    if (storageFile != null)
    {
      var success = Windows.System.Launcher.LaunchFileAsync(storageFile);
    }
  }
  catch (Exception)
  {
    /* If no file can be displayed we send a capptain error */
    throw new CapptainException("URI cannot be opened ");
  }
}

我尝试在App.xaml.cs&#34; OnLaunched&#34;中使用它。方法

这适用于很多URI但是通过附加到http://tozon.info/blog/post/2011/10/06/Windows-8-Metro-declarations-Protocol.aspx我无法在应用启动时将其用于具有自定义方案的URI。这冻结了UI。但是当app已经启动并且我将此功能设置为按钮时,这适用于自定义方案。 我不知道为什么这不适用于app start

1 个答案:

答案 0 :(得分:0)

我知道这是一篇较老的帖子,你可能已经弄清楚了,但我想我有答案。我之前遇到过这样的事情。

如果您的OnActivate和OnProtocolActivate方法与该帖子中的方法完全相同,那么如果应用程序尚未运行,它将无法工作。这是因为您的应用没有框架可供使用。如果没有框架,则无需任何编程工作来设置要加载的视图。如果应用程序已经运行,那么已经有一个框架可以为你工作了,这就是它已经启动的原因。

查看新项目附带的OnLaunched代码。如果它不存在,它们会创建一个新框架。我相信如果您只是在OnProtocolActivated方法的开头添加以下代码,那么它应该可以在应用程序尚未启动时运行。

private void OnProtocolActivated(ProtocolActivatedEventArgs args)
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame == null)
    {                
        rootFrame = new Frame();
        Window.Current.Content = rootFrame;
    }
/// Your code goes after

希望有所帮助。