Home > Software engineering >  How to get unique id of mobile xamarin c#?
How to get unique id of mobile xamarin c#?

Time:12-23

i am trying to retrive a unique id of mobile using mobile xamarin application i am using in

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);
        }

}

and i created a Interface in shared project as

 public interface IDevice
    {
        string GetIdentifier();
    }

i called the function in shaed project as

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

i alawys get

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

CodePudding user response:

You need to add Dependency attribute to the assembly namespace where the class that implements the interface is declared.

Eg.

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

I wouldn't add the class to the MainActivity.cs but create a separate namespace for that.

  • Related