Search code examples
xamarin.formsimeiobsolete

Is there any alternative way for getting IMEI number which wont give me obsolete warning?


Hi I want to get IMEI number in my Android device.And I'm able to do it. But I'm getting obsolete warning saying 'TelephonyManager.DeviceId' is obsolete:'deprecated'. I'm using this code to get IMEI number in my Android device

Android.Telephony.TelephonyManager mTelephonyMgr;
        mTelephonyMgr = (Android.Telephony.TelephonyManager)Forms.Context.GetSystemService(Android.Content.Context.TelephonyService);

        return mTelephonyMgr.DeviceId;

right now I'm able to disable the obsolete warning by using

     mTelephonyMgr = (Android.Telephony.TelephonyManager)Forms.Context.GetSystemService(Android.Content.Context.TelephonyService);
#pragma warning disable CS0618 // Type or member is obsolete
            return mTelephonyMgr.DeviceId;
#pragma warning restore CS0618 // Type or member is obsolete

But why I'm getting this obsolete warning? Is there a different approach for getting IMEI number where I wont get this obsolete warning?


Solution

  • Definition of DeviceId:

    Returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.
    

    When IMEI is simply:

    IMEI (International Mobile Equipment Identity)
    

    From Android official documentation it seems that DeviceId is deprecated from API level 26 and that you should use GetMeid(int slotIndex) instead. In this case I would check the API level and if it is bellow 26 than I would still use DeviceId otherwise GetMeid(int slotIndex).

    Something like this:

    string GetIMEI()
    {
        Android.Telephony.TelephonyManager mTelephonyMgr = (Android.Telephony.TelephonyManager)Forms.Context.GetSystemService(Android.Content.Context.TelephonyService);
        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            // TODO: Some phones has more than 1 SIM card or may not have a SIM card inserted at all
            return mTelephonyMgr.GetMeid(0);
        else
            #pragma warning disable CS0618 // Type or member is obsolete
            return mTelephonyMgr.DeviceId;
            #pragma warning restore CS0618 // Type or member is obsolete
    }