Windows Phone中获取UserAgent

进入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

 

转载自:http://www.developer.nokia.com/Community/Wiki/%E5%9C%A8Windows_Phone%E4%B8%AD%E8%8E%B7%E5%8F%96UserAgent

posted @ 2013-07-17 16:03  jeekun  阅读(2647)  评论(0编辑  收藏  举报