Today am going to retrieve Phone Device Information in an Android Device with Xamarin Form PCL. Lets start by implementing the interface required for the DependencyService
public interface IPhoneInfoService { string GetDevicePhoneNumber(); string GetDeviceID(); string SIMOperatorName(); string SIMSerialNumber(); }
We will now move over the Droid Project and implement the IPhoneInfoService for the project.
class PhoneInfoService : IPhoneInfoService { TelephonyManager m_TeleMgr; public PhoneInfoService() { m_TeleMgr = Application.Context.GetSystemService(Context.TelephonyService) as TelephonyManager; } #region IPhoneInfoService public string GetDeviceID() { return m_TeleMgr.DeviceId; } public string GetDevicePhoneNumber() { return m_TeleMgr.Line1Number; } public string SIMOperatorName() { return m_TeleMgr.SimOperatorName; } public string SIMSerialNumber() { return m_TeleMgr.SimSerialNumber; } #endregion }
Do not forget to decorate your implementation class with Dependency Attribute
[assembly: Xamarin.Forms.Dependency(typeof(PhoneInfoService))]
Finally, it is time to use the method. We will move to PCL project and (for the sake of this example), use it in the contructor of our MainViewModel.cs.
public MainPageViewModel(IPhoneInfoService PhoneInfoService) { m_PhoneInfoService = PhoneInfoService; string ID = m_PhoneInfoService.GetDeviceID(); }
Note that we have used Dependency Injection by overriding the default Constructor and passing the IPhoneInfoService. Make sure you have READ_PHONE_STATE permission set via the manifest. That’s it.