TelephonyManager.getDeviceId(0) returns different

2019-08-03 22:44发布

问题:

For some specific reasons I need to get the IMEI at some point in my Android app. Here is the code I use:

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
    // API available only >= 6.0
    // Get first slot to avoid issue if we have multiple sim cards
    String imei = tm.getDeviceId(0);
}
else
{
    String imei = tm.getDeviceId();
}

It works fine in most cases. However some devices (like the Huawei Honor 7) offer dual-sim capability. In the settings, the user has the possibility to switch between the two SIM cards for 3G/4G support.

When I have two SIM cards and I do that switch, the IMEI I get is different.

As far as I know, the IMEI is related to a physical slot and should not change. This looks like bad implementation from the constructor.

Any idea for a workaround?

回答1:

As you said IMEI/Device Id is tagged to sim slot.

For dual SIM phones there are three IMEI values(one for each slot) and IMEI-SV.

Let’s say IMEI for slot 1 is: 123456789012345

IMEI for slot 2 is: 012500123456789

Depending on the scenarios, following is the returned value by telephonyManagerObj.getDeviceId():

  1. When you don’t have any SIM card, the method will return IMEI for slot1 i.e. 123456789012345
  2. When you have SIM card in slot 1, the method will return IMEI for slot1 i.e. 123456789012345
  3. When you have SIM card in both slots, the method will return IMEI for slot1 i.e. 123456789012345
  4. But when you have SIM card only in slot 2, the method will return IMEI for slot2 i.e. 012500123456789
  5. I found that on one device when I insert the SIM card incorrectly in slot 1 then the method returned IMEI-SV

One work around to maintain consistency is to store the IMEI in SharedPreference/Sqlite once you successfully managed to retrieve it.

So when you need IMEI value in your code, you can first check if its available in your local storage. If not available then retrieve the IMEI and store it for next time usage.

Be careful, getDeviceId() has been deprecated in Android O. Check this so for alternative