Skip to content

Commit 1cb90ba

Browse files
authored
Merge pull request Blankj#779 from fengminchao/master
fix bug when get IMEI on CDMA phones,add getIMEI(int slotId) method
2 parents d3f0a8d + 7089d91 commit 1cb90ba

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

utilcode/lib/src/main/java/com/blankj/utilcode/util/PhoneUtils.java

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import android.telephony.TelephonyManager;
1313
import android.text.TextUtils;
1414

15+
import java.lang.reflect.Method;
1516
import java.util.List;
1617

1718
import static android.Manifest.permission.CALL_PHONE;
@@ -95,8 +96,54 @@ public static String getIMEI() {
9596
//noinspection ConstantConditions
9697
return tm.getImei();
9798
}
98-
//noinspection ConstantConditions
99-
return tm.getDeviceId();
99+
String imei = tm.getDeviceId();
100+
if (imei != null && imei.length() == 15){
101+
return imei;
102+
}else {
103+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
104+
try {
105+
Class clazz = tm.getClass();
106+
Method method = clazz.getDeclaredMethod("getImei");
107+
method.setAccessible(true);
108+
imei = (String) method.invoke(tm);
109+
} catch (Exception e){
110+
}finally {
111+
return imei != null ? imei : "";
112+
}
113+
}else {
114+
return "";
115+
}
116+
}
117+
}
118+
119+
/**
120+
* Return the IMEI.
121+
* <p>Must hold
122+
* {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
123+
*
124+
* @param slotId of which deviceID is returned
125+
* @return the IMEI
126+
*/
127+
@SuppressLint("HardwareIds")
128+
@RequiresPermission(READ_PHONE_STATE)
129+
public static String getIMEI(int slotId){
130+
TelephonyManager tm = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
131+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
132+
return tm.getImei(slotId);
133+
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
134+
String imei = null;
135+
try {
136+
Class clazz = tm.getClass();
137+
Method method = clazz.getDeclaredMethod("getImei",int.class);
138+
method.setAccessible(true);
139+
imei = (String) method.invoke(tm,slotId);
140+
} catch (Exception e){
141+
}finally {
142+
return imei != null ? imei : "";
143+
}
144+
}else {
145+
return getIMEI();
146+
}
100147
}
101148

102149
/**

0 commit comments

Comments
 (0)