与众不同 windows phone (23) - Device(设备)之硬件状态, 系统状态, 网络状态

[索引页]
[源码下载]


与众不同 windows phone (23) - Device(设备)之硬件状态, 系统状态, 网络状态



作者:webabcd


介绍
与众不同 windows phone 7.5 (sdk 7.1) 之设备

  • 硬件状态
  • 系统状态
  • 网络状态



示例
1、演示如何获取硬件的相关状态
HardwareStatus.xaml.cs

/*
 * 演示如何获取设备的硬件信息 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.Windows.Navigation;
using Microsoft.Phone.Info;

namespace Demo.Device.Status
{
    public partial class HardwareStatus : PhoneApplicationPage
    {
        public HardwareStatus()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            lblMsg.Text = "";

            /*
             * DeviceStatus - 用于获取相关的设备信息
             */

            lblMsg.Text += "设备制造商:" + DeviceStatus.DeviceManufacturer;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "设备名称:" + DeviceStatus.DeviceName;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "物理内存总计:" + DeviceStatus.DeviceTotalMemory; // 单位:字节
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "系统分给当前应用程序的最大可用内存:" + DeviceStatus.ApplicationMemoryUsageLimit; // 单位:字节
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "当前应用程序占用内存的当前值:" + DeviceStatus.ApplicationCurrentMemoryUsage; // 单位:字节
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "当前应用程序占用内存的高峰值:" + DeviceStatus.ApplicationPeakMemoryUsage; // 单位:字节
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "硬件版本:" + DeviceStatus.DeviceHardwareVersion;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "固件版本:" + DeviceStatus.DeviceFirmwareVersion;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "设备是否包含物理键盘:" + DeviceStatus.IsKeyboardPresent;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "物理键盘是否正在使用:" + DeviceStatus.IsKeyboardDeployed;
            lblMsg.Text += Environment.NewLine;

            /*
             * Microsoft.Phone.Info.PowerSource 枚举 - 供电方式
             *     Battery - 电池
             *     External - 外接电源
             */
            lblMsg.Text += "供电方式:" + DeviceStatus.PowerSource; 
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "是否支持多分辨率编码视频的平滑流式处理:" + MediaCapabilities.IsMultiResolutionVideoSupported;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "设备标识:" + GetDeviceUniqueId();
            
            // 当物理键盘的使用状态(使用或关闭)发生改变时所触发的事件
            DeviceStatus.KeyboardDeployedChanged += new EventHandler(DeviceStatus_KeyboardDeployedChanged);

            // 当设备的供电方式(电池或外接电源)发生改变时所触发的事件
            DeviceStatus.PowerSourceChanged += new EventHandler(DeviceStatus_PowerSourceChanged);
        }

        void DeviceStatus_PowerSourceChanged(object sender, EventArgs e)
        {
            MessageBox.Show("供电方式:" + DeviceStatus.PowerSource);
        }

        void DeviceStatus_KeyboardDeployedChanged(object sender, EventArgs e)
        {
            MessageBox.Show("物理键盘是否正在使用:" + DeviceStatus.IsKeyboardDeployed);
        }

        /// <summary>
        /// 获取设备的唯一ID
        /// </summary>
        private string GetDeviceUniqueId()
        {
            string result = "";
            object uniqueId;
            /*
             * DeviceExtendedProperties.TryGetValue() - 用于获取设备的唯一ID
             */
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
            {
                result = ByteToHexStr((byte[])uniqueId);

                if (result != null && result.Length == 40)
                    result = result.Insert(8, "-").Insert(17, "-").Insert(26, "-").Insert(35, "-");
            }

            return result;
        }

        /// <summary>
        /// 将一个字节数组转换为十六进制字符串
        /// </summary>
        private string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
    }
}


2、演示如何获取系统的相关状态
SystemStatus.xaml.cs

/*
 * 演示如何获取设备的系统信息 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.Windows.Navigation;
using System.Globalization;
using Microsoft.Phone.Info;

namespace Demo.Device.Status
{
    public partial class SystemStatus : PhoneApplicationPage
    {
        public SystemStatus()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            lblMsg.Text = "";

            // System.PlatformID 枚举 - 包括 Win32S, Win32Windows, Win32NT, WinCE, Unix, Xbox, NokiaS60
            lblMsg.Text += "系统内核:" + Environment.OSVersion.Platform; // System.PlatformID 枚举
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "系统版本:" + Environment.OSVersion.Version; // System.Version 类型的对象
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "CLR 版本:" + Environment.Version; // System.Version 类型的对象
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "系统自上次启动以来所经过的毫秒数:" + Environment.TickCount;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "当前语言:" + CultureInfo.CurrentCulture.DisplayName;
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "当前时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + " 星期" + "日一二三四五六七".Substring((int)DateTime.Now.DayOfWeek, 1);
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "当前时区:" + "UTC" + DateTimeOffset.Now.ToString("%K");
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "主题 - 背景色:" + GetThemeBackground();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "主题 - 主题色:" + GetThemeAccent();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "Live ID:" + GetWindowsLiveAnonymousId();
        }

        /// <summary>
        /// 获取当前设备主题的背景色
        /// </summary>
        private string GetThemeBackground()
        {
            string background = "";
            Visibility darkBackgroundVisibility = (Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"];

            if (darkBackgroundVisibility == Visibility.Visible)
                background = "";
            else
                background = "";

            return background;
        }

        /// <summary>
        /// 获取当前设备主题的主题色
        /// </summary>
        private string GetThemeAccent()
        {
            string accent = "";
            Color currentAccentColorHex = (Color)Application.Current.Resources["PhoneAccentColor"];

            switch (currentAccentColorHex.ToString())
            {
                case "#FF1BA1E2":
                    accent = "";
                    break;
                case "#FFA05000":
                    accent = ""; 
                    break;
                case "#FF339933": 
                    accent = "绿"; 
                    break;
                case "#FFE671B8": 
                    accent = "粉红"; 
                    break;
                case "#FFA200FF": 
                    accent = ""; 
                    break;
                case "#FFE51400": 
                    accent = ""; 
                    break;
                case "#FF00ABA9": 
                    accent = ""; 
                    break;
                case "#FF8CBF26": // (sdk 7.0)
                case "#FFA2C139": // (sdk 7.1)
                    accent = "黄绿"; 
                    break;
                case "#FFFF0097": // (sdk 7.0)
                case "#FFD80073": // (sdk 7.1)
                    accent = "洋红"; 
                    break;
                case "#FFF09609": 
                    accent = ""; 
                    break;
                case "#FF1080DD":
                    accent = "诺基亚蓝";
                    break;
                default: 
                    accent = currentAccentColorHex.ToString(); 
                    break;
            }

            return accent;
        }

        /// <summary>
        /// 当绑定了 Live 账号后,此方法可以获取到用户的唯一 ID(匿名标识)
        /// </summary>
        private string GetWindowsLiveAnonymousId()
        {
            string result = string.Empty;
            object anid;

            if (UserExtendedProperties.TryGetValue("ANID", out anid))
            {
                if (anid != null && anid.ToString().Length >= 34)
                {
                    result = new Guid(anid.ToString().Substring(2, 32)).ToString();
                }
            }

            return result;
        }
    }
}


3、演示如何获取网络的相关状态
NetworkStatus.xaml.cs

/*
 * 演示如何获取设备的网络信息 
 */

using System;
using System.Linq;
using System.Net;
using Microsoft.Phone.Controls;

using System.Windows.Navigation;
using Microsoft.Phone.Net.NetworkInformation;
using System.Threading;
using System.Windows;

namespace Demo.Device.Status
{
    public partial class NetworkStatus : PhoneApplicationPage
    {
        public NetworkStatus()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            lblMsg.Text = "异步获取网络信息,可能较慢。。。";
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;

            ThreadPool.QueueUserWorkItem(DeviceNetworkInformationDemo);
            ThreadPool.QueueUserWorkItem(NetworkInterfaceInfoDemo);
            ThreadPool.QueueUserWorkItem(ResolveHostNameAsyncDemo);
        }

        private void DeviceNetworkInformationDemo(object state)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                /*
                 * DeviceNetworkInformation - 用于获取相关的网络信息
                 */

                lblMsg.Text += "运营商名称:" + DeviceNetworkInformation.CellularMobileOperator;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "是否启用了手机网络数据连接:" + DeviceNetworkInformation.IsCellularDataEnabled;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "是否启用了手机网络数据漫游:" + DeviceNetworkInformation.IsCellularDataRoamingEnabled;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "是否启用了 WiFi 网络:" + DeviceNetworkInformation.IsWiFiEnabled;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "网络是否可用:" + DeviceNetworkInformation.IsNetworkAvailable;
                lblMsg.Text += Environment.NewLine;

                /*
                 * NetworkInterfaceType - 网络接口的类型(Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType 枚举)
                 */
                lblMsg.Text += "数据网络接入类型:" + NetworkInterface.NetworkInterfaceType;
                lblMsg.Text += Environment.NewLine;
            });

            /*
             * NetworkAvailabilityChanged - 连接网络、断开网络或更改漫游状态时触发的事件
             */
            DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(DeviceNetworkInformation_NetworkAvailabilityChanged);
        }

        void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            /*
             * NetworkNotificationEventArgs.NetworkInterface - 返回当前的 NetworkInterfaceInfo 对象
             * 
             * NetworkNotificationEventArgs.NotificationType - 返回 Microsoft.Phone.Net.NetworkInformation.NetworkNotificationType 枚举类型的数据
             *     InterfaceConnected - 已连接
             *     InterfaceDisconnected - 连接已断开
             *     CharacteristicUpdate - 连接更新(如打开或关闭漫游)
             */

            this.Dispatcher.BeginInvoke(delegate()
            {
                switch (e.NotificationType)
                {
                    case NetworkNotificationType.InterfaceConnected:
                        lblMsg.Text += "已连接到:" + e.NetworkInterface.InterfaceName + "(" + e.NetworkInterface.InterfaceType + ")";
                        break;
                    case NetworkNotificationType.InterfaceDisconnected:
                        lblMsg.Text += "已从此断开:" + e.NetworkInterface.InterfaceName + "(" + e.NetworkInterface.InterfaceType + ")";
                        break;
                    case NetworkNotificationType.CharacteristicUpdate:
                        lblMsg.Text += "连接更新(如打开或关闭漫游):" + e.NetworkInterface.InterfaceName + "(" + e.NetworkInterface.InterfaceType + ")";
                        break;
                    default:
                        lblMsg.Text += "未知变化,当前连接为:" + e.NetworkInterface.InterfaceName + "(" + e.NetworkInterface.InterfaceType + ")";
                        break;
                }

                lblMsg.Text += Environment.NewLine;
            });
        }

        private void NetworkInterfaceInfoDemo(object state)
        {
            /*
             * NetworkInterfaceList - NetworkInterfaceInfo 的集合
             * 
             * NetworkInterfaceInfo - 单个网络接口的相关信息
             */

            NetworkInterfaceList interfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo interfaceInfo = interfaceList.First();

            this.Dispatcher.BeginInvoke(delegate()
            {
                lblMsg.Text += "网络接口的名称:" + interfaceInfo.InterfaceName;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "网络接口的类型:" + interfaceInfo.InterfaceType; // Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType 枚举
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "网络接口的类型的其他信息:" + interfaceInfo.InterfaceSubtype; // Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceSubType 枚举
                lblMsg.Text += Environment.NewLine;

                /*
                 * InterfaceState - Microsoft.Phone.Net.NetworkInformation.ConnectState 枚举
                 *     Disconnected, Connected
                 */
                lblMsg.Text += "网络接口的状态:" + interfaceInfo.InterfaceState;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "网络接口的速度:" + interfaceInfo.Bandwidth; // 单位:Kb/s
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += "网络接口的说明:" + interfaceInfo.Description;
                lblMsg.Text += Environment.NewLine;

                /*
                 * Characteristics - Microsoft.Phone.Net.NetworkInformation.NetworkCharacteristics 枚举
                 *     None - 没有什么特殊属性
                 *     Roaming - 漫游
                 */
                lblMsg.Text += "网络接口的属性:" + interfaceInfo.Characteristics;
                lblMsg.Text += Environment.NewLine;
            });
        }

        private void ResolveHostNameAsyncDemo(object state)
        {
            /*
             * DeviceNetworkInformation.ResolveHostNameAsync(DnsEndPoint endPoint, NetworkInterfaceInfo networkInterface, NameResolutionCallback callback, Object context) - 异步解析指定的主机名(ping)
             *     DnsEndPoint endPoint - 主机名
             *     NetworkInterfaceInfo networkInterface - 解析主机名所使用的网络接口(可以不指定)
             *     NameResolutionCallback callback - 解析主机名完成后的回调,委托的参数为 NameResolutionResult 类型
             *     Object context - 异步过程中的上下文
             *     
             * NameResolutionResult - 主机名解析完成后的结果
             *     AsyncState - 上下文对象
             *     HostName - 提交解析的主机名
             *     NetworkErrorCode - 结果状态(Microsoft.Phone.Net.NetworkInformation.NetworkError 枚举)
             *     NetworkInterface - 用于解析主机名的网络接口
             *     IPEndPoints - 解析结果,获取到指定主机名的 IP
             *         注:如果被解析的主机名是个 cname 的话,那么这里会获得两个 IP,第一个ip是cname服务器的,第二个ip是cname所映射到的服务器的
             */

            DeviceNetworkInformation.ResolveHostNameAsync
            (
                new DnsEndPoint("www.baidu.com", 80),
                new NameResolutionCallback(nrc =>
                {
                    if (nrc.NetworkErrorCode == NetworkError.Success)
                    {
                        this.Dispatcher.BeginInvoke(delegate()
                        {
                            foreach (IPEndPoint ipEndPoint in nrc.IPEndPoints)
                            {
                                lblMsg.Text += "www.baidu.com - ip:" + ipEndPoint.ToString();
                                lblMsg.Text += Environment.NewLine;
                            }
                        });
                    }
                }),
                null
            );
        }
    }
}



OK
[源码下载]

posted @ 2012-08-20 08:34  webabcd  阅读(3786)  评论(6编辑  收藏  举报