进入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 οnlοad=""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;
});
}