如何在Xamarin Forms中获取设备ID?

27

如何在Xamarin Forms中使用C#获取Android和iOS设备的唯一标识?我正在使用Azure Notification Hub发送通知。我正在参考这篇博客。但是,在Android中我找不到相关的“设置”。


1
你尝试过什么?我们不会在没有尝试过任何东西的情况下提供完整的解决方案。 - David
1
请更新您迄今为止完成的代码或阅读此链接:https://stackoverflow.com/help/how-to-ask - FreakyAli
你可以使用XamarinEssentials的设备信息来获取设备信息。然后,你可以通过组合制造商+型号+总内存+设备名称等硬件值来生成设备ID。然而,建议使用会话标识符。你必须生成带有过期日期的会话ID。请在提问时始终完整。始终提及一个简要的场景,你尝试过什么,以及你的期望。尊重其他开发者宝贵的时间,并提供所有必要的细节,以便他们了解你的场景的要点。 - undefined
3个回答

42
根据您发布的博客文章 http://codeworks.it/blog/?p=260 以及您简短的问题描述,我会尝试回答您的问题。
对于 Android,请使用以下代码获取设备 ID: Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId); 对于 iOS,请查看您的博客文章。或者可将 IdentifierForVendor 保存在 AppDelegate 中,并在 IOSDevice 类中返回该值(使用博客文章中的名称)。使用 UIDevice.CurrentDevice.IdentifierForVendor.ToString() 获取 iOS 设备的 ID。

5
对于Android开发而言,Forms.Context已经过时,请使用Android.App.Application.Context代替。 - Baqer Naqvi
如果您在使用Android.Provider时遇到错误,请使用"global::Android.Provider"。 - cho
1
我认为在你的应用程序中存储用户设备ID是非法的,但我可能错了。 - c-sharp-and-swiftui-devni
2
注意!'UIDevice.CurrentDevice.IdentifierForVendor.ToString()' 只会给你一个新的 GUID。当你删除并重新安装应用程序时,该值将会改变。因此它并不是设备的确切 ID。 - ayberkzeray
我在5个应用程序中使用了Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);,但其中一个应用程序返回了不同的设备 ID,而其他4个应用程序返回相同的设备 ID。我在同一台设备上测试了这5个应用程序。 - Deepak yogi

15

这里详细描述了如何为移动应用生成唯一设备ID。但实际上,您不需要像这样尝试从每个设备获取一个ID。只需创建一个Guid并保存到设备上即可运行。Xamarin拥有Preferences功能,可将值持久化在设备上。

您可以像我下面所做的那样创建一个guid并将其保存到Preferences中:

var deviceId = Preferences.Get("my_deviceId", string.Empty);
if(string.IsNullOrWhitespace(deviceId))
{
  deviceId = System.Guid.NewGuid().ToString();
  Preferences.Set("my_deviceId", deviceId);
}

采用这种方法的好处是在您将应用程序转移到另一个设备后,您仍将拥有相同的ID;但是,如果您卸载并重新安装,则会获得新的ID。对于从设备获取ID的其他情况,在将应用程序转移到另一个设备时,它将发生变化。

对于您想从设备获取ID的其他情况:

iOS:IdentifierForDevice

public string Id => UIDevice.CurrentDevice.IdentifierForVendor.AsString();

Android: Serial、getSerial和AndroidId

    string id = string.Empty;
    public string Id
    {
        get
        {
            if (!string.IsNullOrWhiteSpace(id))
                return id;

            id = Android.OS.Build.Serial;
            if (string.IsNullOrWhiteSpace(id) || id == Build.Unknown || id == "0")
            {
                try
                {
                    var context = Android.App.Application.Context;
                    id = Secure.GetString(context.ContentResolver, Secure.AndroidId);
                }
                catch (Exception ex)
                {
                    Android.Util.Log.Warn("DeviceInfo", "Unable to get id: " + ex.ToString());
                }
            }

            return id;
        }
    }

UWP:GetPackageSpecificToken或GetSystemIdForPublisher

 string id = null;
    public string Id
    {
        get
        {

            if (id != null)
                return id;

            try
            {
                if (ApiInformation.IsTypePresent("Windows.System.Profile.SystemIdentification"))
                {
                    var systemId = SystemIdentification.GetSystemIdForPublisher();

                    // Make sure this device can generate the IDs
                    if (systemId.Source != SystemIdentificationSource.None)
                    {
                        // The Id property has a buffer with the unique ID
                        var hardwareId = systemId.Id;
                        var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

                        var bytes = new byte[hardwareId.Length];
                        dataReader.ReadBytes(bytes);

                        id = Convert.ToBase64String(bytes);
                    }
                }

                if (id == null && ApiInformation.IsTypePresent("Windows.System.Profile.HardwareIdentification"))
                {
                    var token = HardwareIdentification.GetPackageSpecificToken(null);
                    var hardwareId = token.Id;
                    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

                    var bytes = new byte[hardwareId.Length];
                    dataReader.ReadBytes(bytes);

                    id = Convert.ToBase64String(bytes);
                }

                if (id == null)
                {
                    id = "unsupported";
                }

            }
            catch (Exception)
            {
                id = "unsupported";
            }

            return id;
        }
    }

3
除了技术原因之外,我还会采用应用程序/设备GUID存储的方法,以避免伪名化带来的任何监管问题。物理设备ID可能被视为个人数据。+1! - Frank
假设您的用户需要登录,您已经拥有特定于用户的身份标识。生成GUID的好处是什么?我还没有遇到过不要求某种形式的用户标识(通常是电子邮件)的应用程序。 - ToolmakerSteve
使用生成的 GUID 不是设备 ID,并且在重置时会被轻易删除,因此您的“设备 ID”将会改变。我建议不要使用这种方法。我曾经使用 IMEI,但当然现在已不可用。请看 Erdogan 的建议。 - Mark Anderson

1

1
据我所知,此插件的所有功能也都包含在Xamarin.Essentials中。 - this.myself
1
@this.myself,你能分享文档链接吗?我在https://learn.microsoft.com/en-us/xamarin/essentials/device-information?tabs=ios上找不到它。 - Erdogan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接