【问题标题】:How to get unique id of mobile xamarin c#?如何获取移动 xamarin c# 的唯一 ID?
【发布时间】:2025-12-07 20:15:02
【问题描述】:

我正在尝试使用我正在使用的移动 xamarin 应用程序检索移动设备的唯一 ID

MainActivity.Cs

public class AndroidDevice : IDevice
    {

        public string GetIdentifier()
        {
            var context = Android.App.Application.Context;
            return Android.Provider.Settings.Secure.GetString(context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
        }

}

我在共享项目中创建了一个接口

 public interface IDevice
    {
        string GetIdentifier();
    }

我将shaed项目中的函数称为

string deviceIdentifier = DependencyService.Get<IDevice>().GetIdentifier();

我知道了

System.NullReferenceException: 'Object reference not set to an instance of an object.'

【问题讨论】:

  • 什么是空?您的 DependencyService.Get() 调用很可能返回 null,因为它无法解析引用。您是否按照 DependencyService 文档中的所有说明进行操作?
  • string deviceIdentifier is alawys null,

标签: c# xamarin


【解决方案1】:

您需要在程序集命名空间中添加Dependency 属性,其中声明了实现该接口的类。

例如。

[assembly: Dependency(typeof(DroidImplementation))]
namespace MyApp.Droid.Implementation
{
    public class DroidImplementation : IMyInterface
    {
       // your class implementation here
    }
}

我不会将该类添加到 MainActivity.cs,而是为此创建一个单独的命名空间。

【讨论】: