Device Information in XF PCL

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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s