Sometimes we need to get device information like OS version, device, manufacturer etc. Such information we can get using android.os.Build class. To get phone related detail like IEMI, IMSI, deviceId, mobile number we can use TelephonyManager. To get phone related information we must request READ_PHONE_STATE permission in AndroidManifest.xml.
Due to security reasons, we can't get mobile number of a android device programmatically. Here is the code to get mobile number...
TelephonyManager mgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = mgr.getLine1Number();
The above code can return correct mobile number but it can also return null or "" or even "???????", and it can return a stale phone number that is no longer valid. So, if we need something that uniquely identifies the device, we should use getDeviceId() instead.
Lets try to implement a sample to get device information in android device.
Result of the this sample is...
Source code of above sample is straight forward. Lets try to understand code of all attached files.
MainActivity.java : Before Android 6.0( Api level 23), user was granting permission at the time of app installation. But from Adroid 6.0(Api level 23) and onward, application need to request permission that are in dangerous nature at run time. I will explain requesting and granting user's permission at run time in seprate thread.
Inside onCreate method, I am checking if sdk version of user's device is greater or equals to 23, then I am initiating permission request at runtime by calling requestPermission() method, In other case we don't need permission request.
Once user grants or denies permission request, android system calls onRequestPermissionsResult method. I am checking wether user has granted permission, if so then string permission status in a variable.
showDeviceInfo method is called when user click on button, here I am checking permission status showing message accordingly.
In string.xml I stored string resource of my app
In AndroidManifest.java, I've just added