×
Namespaces

Variants
Actions

在Windows Phone中获取UserAgent

From Nokia Developer Wiki
Jump to: navigation, search
SignpostIcon XAML 40.png
SignpostIcon WP7 70px.png
Article Metadata

代码示例
测试基于
SDK: Windows Phone SDK 8.0

兼容于
文章
Xinx Gong 在 16 Jul 2013 创建
最后由 hamishwillee 在 26 Jul 2013 编辑

Contents

介绍

进入WP8时代后,通过DeviceExtendedProperties获取到的DeviceName不再是手机型号了,这对于需要获得手机型号做一些事情的应用(如新浪微博的小尾巴)来说,影响是比较大的。 这时候我们就需要通过获取手机的UserAgent来取得这个手机型号。由于在Windows Phone中并没有直接获取UserAgent的API,所以我们需要通过WebBrowser解析一个特定的html字符串来间接的获取,下面来看看具体的实现步骤:

1.定义获取UserAgent使用的HTML

        private const string Html =
@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"">
<html>
<head>
<script language="
"javascript"" type=""text/javascript"">
function notifyUA() {
window.external.notify(navigator.userAgent);
}
</script>
</head>
<body onload="
"notifyUA();""/>
</html>"
;

2.使用WebBrowser解析HTML

        public static void GetUserAgent(Panel rootElement, Action<string> callback)
{
var browser = new Microsoft.Phone.Controls.WebBrowser();
browser.IsScriptEnabled = true;
browser.Visibility = Visibility.Collapsed;
browser.Loaded += (sender, args) => browser.NavigateToString(Html);
browser.ScriptNotify += (sender, args) =>
{
string userAgent = args.Value;
rootElement.Children.Remove(browser);
callback(userAgent);
};
rootElement.Children.Add(browser);
}

3.获取UserAgent

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
GetUserAgent(
LayoutRoot,
userAgent =>
{
UserAgentTextBlock.Text = userAgent;
});
}

Wp ss 20130716 0001.png

示例代码下载

File:UserAgentExample.zip

This page was last modified on 26 July 2013, at 03:00.
123 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×