我尝试了以下代码:
private String getImsi() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getSubscriberId();
}
<uses-permission android:name='android.permission.READ_PHONE_STATE' />
但它只返回null。
有没有其他方法可以在android中使用java获取IMSI?
答案 0 :(得分:2)
String imei = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
获得许可
android.permission.READ_PHONE_STATE
由于SystemProperties是Android中的隐藏类,因此您可以使用反射访问它:
/**
* Get the value for the given key.
* @return an empty string if the key isn't found
*/
public static String get(Context context, String key) {
String ret = "";
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes= new Class[1];
paramTypes[0]= String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[1];
params[0] = new String(key);
ret = (String) get.invoke(SystemProperties, params);
} catch(Exception e) {
ret = "";
//TODO : Error handling
}
return ret;
}
答案 1 :(得分:1)
您是否在清单中添加了此权限?
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
编辑: 好的,试试这个:
String myIMSI =
android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
SystemProperties它是一个隐藏的类。试着点击这里:https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/SystemProperties.java