vendredi 5 septembre 2014

Quick Tip: Getting Device ID on Windows & Windows Phone

When building out apps, there are some situations where you are required to get a unique ID of the device whether it be for analytic data or to potentially limit devices from accessing some private services.
This quick tip will show you how to get the device ID on different platforms such as Windows Phone 7, Windows Phone 8 and Windows 8.

Windows Phone 7

To get device ID on Windows Phone 7 you can use the following

private string m_DeviceUniqueId;
public string DeviceId
{
    get
    {
        if (m_DeviceUniqueId == null)
        {
            object val;
            if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out val))
                m_DeviceUniqueId = Convert.ToBase64String((val as byte[]));
        }
        return m_DeviceUniqueId;
    }
}



Windows Phone 8

Getting device ID on Windows Phone 8 is slightly different the the previous version and can be accomplished with the following

private string m_DeviceUniqueId;
public string DeviceId
{
    get
    {
        if (m_DeviceUniqueId == null)
        {
            m_DeviceUniqueId = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
        }
        return m_DeviceUniqueId;
    }
}


Windows 8

On Windows 8, it’s yet another API to get the device ID and can be accomplished with the following


private string m_DeviceUniqueId;
public string DeviceId
{
    get
    {
        if (m_DeviceUniqueId == null)
        {
            var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
            var hardwareId = token.Id;
            var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);
 
            byte[] bytes = new byte[hardwareId.Length];
            dataReader.ReadBytes(bytes);
 
            m_DeviceUniqueId = BitConverter.ToString(bytes).Replace("-","");
        }
        return m_DeviceUniqueId;
    }
}



Enjoy!

Aucun commentaire:

Enregistrer un commentaire