Reputation: 391
I tried the following code:
private String getImsi() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getSubscriberId();
}
<uses-permission android:name='android.permission.READ_PHONE_STATE' />
But it only returns null.
Is there any other way to obtain the IMSI with java in android?
Upvotes: 4
Views: 15650
Reputation: 1
The following solution works only for system applications:
private String getIMSI(){
telephonyManager = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);
return telephonyManager.getSubscriberId();
}
In AndroidManifest.xml add permissions:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
The second permission is marked as system
Works in Android 9 (API 28).
Upvotes: 0
Reputation: 3723
String imei = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
with permission
android.permission.READ_PHONE_STATE
Since SystemProperties is a hidden class in Android, you can access it with reflection:
/**
* 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;
}
Upvotes: 2
Reputation: 5904
Did you add this permission in the manifest?
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Edit: ok, try use this one:
String myIMSI =
android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
SystemProperties it's an hidden class. try to check here: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/SystemProperties.java
Upvotes: 1