Windows Phone 8/Windows 8 启动第三方应用程序并传递参数

时间:2022-03-22 16:59:02

  需要被其他应用启动的第三方应用需要注册protocol association,当一个应用程序启动一个特殊的URI的时候,那么注册了这个protocol的程序会自动启动,并且可以通过这个特殊的URI将参数传递到第三方应用中。

第三方应用程序注册protocol association步骤

  Windows Phone 8 和 Windows 8 注册方式有一些差异,下面分别说明注册方式。

Windows Phone 8第三方应用程序注册Protocol

  1.修改WPAppManifest.xaml文件

  在</Token>后面添加类似如下代码:

 <Extensions>
  <Protocol Name="testapp" NavUriFragment="encodedLaunchUri=%s" TaskID="_default"/>
</Extensions>

  MSDN关于Protocol标签的说明参考:Windows Phone 的应用清单文件

  Protocol 元素是 Extensions 元素的子元素,始终应该跟在所有 FileTypeAssociation 元素后面。Protocol 元素说明了应用注册的 URI 方案名称,使其可以在另一个应用启动某个特定 URI 时启动。有关更多信息,请参见 使用 Windows Phone 8 文件和 URI 关联的自动启动应用

属性

类型

说明

Name

String

自定义的 URI 方案的前缀。包含数字、小写字母、句点 (‘.’) 或连字符 (‘-’) 且长度介于 2 和 39 个字符的字符串。不包含冒号 (‘:’)或任何在 URI 中的前缀后面的内容。

NavUriFragment

String

始终设置为   encodedLaunchUri=%s。

TaskID

String

始终设置为   _default。

  2.添加URI请求解析处理程序

  传人程序的UIR格式为:/Protocol?encodedLaunchUri={传人的URI},为了使程序能够正确解析传人的URI,需要为工程添加AssociationUriMapper类,代码如下:

     /// <summary>
/// 解析第三方应用调用参数
/// </summary>
class AssociationUriMapper : UriMapperBase
{
private string tempUri; public override Uri MapUri(Uri uri)
{
tempUri = uri.ToString(); // Protocol association launch for contoso.
if (tempUri.Contains("/Protocol"))
{
int pos = tempUri.IndexOf("encodedLaunchUri");
String encodedString = tempUri;
if (pos >= )
{
encodedString = tempUri.Substring(pos);
}
return new Uri("/MainPage.xaml?" + encodedString, UriKind.Relative);
} // Include the original URI with the mapping to the main page.
return new Uri("/MainPage.xaml", UriKind.Relative);
}
}

  3.修改App.xaml.cs文件的InitializePhoneApplication,添加:

             // Assign the URI-mapper class to the application frame.
RootFrame.UriMapper = new AssociationUriMapper();

  4.修改MainPage.xaml.cs文件,添加提示框,弹出传人的URI,代码如下:

         protected override async void OnNavigatedTo(NavigationEventArgs e)
{
//解析第三方应用调用参数
if (NavigationContext.QueryString.ContainsKey("encodedLaunchUri"))
{
String launchuri = NavigationContext.QueryString["encodedLaunchUri"];
MessageBox.Show(launchuri);
//launchuri为传人的URI,解析并保存传人的参数
//-----TO DO--------------
}
}

Windows 8第三方应用程序注册Protocol

  1.修改Package.appxmanifest文件

  找到<Application>标签的子标签<Extensions>,如果不存在,则添加一个。为<Extensions>添加子标签:

 <Extension Category="windows.protocol">
<Protocol Name="testapp" />
</Extension>

  2.修改App.xaml.cs文件,添加如下代码

         protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args); //第三方应用调用处理
if (args.Kind == ActivationKind.Protocol)
{
var protocolArgs = args as ProtocolActivatedEventArgs;
String uristring = protocolArgs.Uri.AbsoluteUri;
//uristring为传人的URI,解析并保存传人的参数
//-----TO DO--------------
}
Window.Current.Activate();
}

第三方应用调用方式  

  Windows Phone 8 和 Windows 8 调用方式相同,格式为:testapp:xxxxxxxxx,其中:testapp为注册Protocol的name。实例代码如下:

Windows.System.Launcher.LaunchUriAsync(new Uri("testapp://type/?param1=value1&param2=value2&param3=value3 "));