Related
I am getting the IMEI ID null from the telephonymanager. What to do?
is there any workaround for that?
Android Q has restricted to access for both IMEI and serial no. It is available only for platform and apps with special carrier permission. Also the permission READ_PRIVILEGED_PHONE_STATE is not available for non platform apps.
If you try to access it throws below exception
java.lang.SecurityException: getImeiForSlot: The user 10180 does not meet the requirements to access device identifiers.
Please refer documentation:
https://developer.android.com/preview/privacy/data-identifiers#device-ids
Also refer Issue
I am late to post answer. I still believe my answer will help someone.
Android 10 Restricted developer to Access IMEI number.
You can have a alternate solution by get Software ID. You can use software id as a unique id. Please find below code as i use in Application.
public static String getDeviceId(Context context) {
String deviceId;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
deviceId = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.ANDROID_ID);
} else {
final TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId();
} else {
deviceId = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.ANDROID_ID);
}
}
return deviceId;
}
This just would not work as of Android Q. Third party apps can not use IMEI nor the serial number of a phone and other non-resettable device identifiers.
The only permissions that are able to use those is READ_PRIVILEGED_PHONE_STATE and that cannot be used by any third party apps - Manufacture and Software Applications. If you use that method you will get an error Security exception or get null .
You can still try to get a unique id by using:
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),Secure.ANDROID_ID);
The best way to get the IMEI number is as follows:
public static String getIMEIDeviceId(Context context) {
String deviceId;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
{
deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
} else {
final TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return "";
}
}
assert mTelephony != null;
if (mTelephony.getDeviceId() != null)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
deviceId = mTelephony.getImei();
}else {
deviceId = mTelephony.getDeviceId();
}
} else {
deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
Log.d("deviceId", deviceId);
return deviceId;
}
Just copy the method and use it. It will definitely. However, you might know you can't get IMEI in android Q (version 10). In this code, you can get a unique identifier (alternative id) through any device or any API level.
It works 100%
Thank You!!
And Enjoy Coding :)
As the best practices suggest. " you can avoid using hardware identifiers, such as SSAID (Android ID) and IMEI, without limiting required functionality."
Rather go for an instance ID such as String uniqueID = UUID.randomUUID().toString(); or FirebaseInstanceId.getInstance().getId();
Not sure about IMEI number, but you can get the simSerialNumber and other carrier info this way.
getSimSerialNumber() needs privileged permissions from Android 10 onwards, and third party apps can't register this permission.
See : https://developer.android.com/about/versions/10/privacy/changes#non-resettable-device-ids
A possible solution is to use the TELEPHONY_SUBSCRIPTION_SERVICE from Android 5.1, to retrieve the sim serial number. Steps below:
Check for READ_PHONE_STATE permission.
Get Active subscription list.( Returns the list of all active sim cards)
Retrieve the sim details from Subscription Object.
if ( isPermissionGranted(READ_PHONE_STATE) ) {
String simSerialNo="";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
SubscriptionManager subsManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
List<SubscriptionInfo> subsList = subsManager.getActiveSubscriptionInfoList();
if (subsList!=null) {
for (SubscriptionInfo subsInfo : subsList) {
if (subsInfo != null) {
simSerialNo = subsInfo.getIccId();
}
}
}
} else {
TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
simSerialNo = tMgr.getSimSerialNumber();
}
}
Check if this helps
you can change other way, i use uuid to replace devices id.
String uniquePseudoID = "35" +
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 +
Build.HOST.length() % 10 +
Build.ID.length() % 10 +
Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 +
Build.TYPE.length() % 10 +
Build.USER.length() % 10;
String serial = Build.getRadioVersion();
String uuid = new UUID(uniquePseudoID.hashCode(), serial.hashCode()).toString();
AppLog.d("Device ID",uuid);
If your app targets Android 10 or higher, a SecurityException occurs.
Following modules are affected...
Build
getSerial()
TelephonyManager
getImei()
getDeviceId()
getMeid()
getSimSerialNumber()
getSubscriberId()
So you cant get IMEI no for android 10 , You have to used another unique identifier for this like Android ID
It unique 64 bit hex no for device
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
According to google docs.
Restriction on non-resettable device identifiers
Starting in Android 10, apps must have the READ_PRIVILEGED_PHONE_STATE privileged permission in order to access the device's non-resettable identifiers, which include both IMEI and serial number.
Caution: Third-party apps installed from the Google Play Store cannot
declare privileged permissions.
So, Instead of imei you can get Android unique ID.
String imei = "";
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
if (telephonyManager != null) {
try {
imei = telephonyManager.getImei();
} catch (Exception e) {
e.printStackTrace();
imei = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1010);
}
} else {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
if (telephonyManager != null) {
imei = telephonyManager.getDeviceId();
}
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1010);
}
}
Targeting Android Q, third party apps can't access IMEI at all. Android Q doc is misleading while stating
Starting in Android Q, apps must have the READ_PRIVILEGED_PHONE_STATE
privileged permission in order to access the device's non-resettable
identifiers, which include both IMEI and serial number.
https://developer.android.com/preview/privacy/data-identifiers#device-ids
But when I actually tried to implement it, I am receiving this exception:
java.lang.SecurityException: getDeviceId: The user 10132 does not meet the requirements to access device identifiers.
Someone had reported this on google's issue tracker where a Googler said that this is intended behaviour and IMEI on Q+ is only available for system level apps.
Status: Won't Fix (Intended Behavior) This is Working As Intended.
IMEI is a personal identifier and this is not given out to apps as a
matter of policy. There is no workaround.
https://issuetracker.google.com/issues/129583175#comment10
They mentioned:
If your app is the device or profile owner app, you need only the READ_PHONE_STATE permission to access non-resettable device identifiers, even if your app targets Android 10 or higher.
I tried deploying via EMM as device owner app but not success.
If you needed, you can try to install a work profile in to the mobile phone and include your app in the same package or vice versa.
I tried and it works, it's simple if yo follow this repo: https://github.com/googlesamples/android-testdpc
When you install the Work Profile your app is installed in this profile and you will have acces to the IMEI.
And now there is another example fixed yesterday to Android 10:
https://github.com/android/enterprise-samples/pull/29
I tried using below piece of code but it is not giving me the number. Your information would be great help.
Code below:
val subscription =SubscriptionManager.from(context).activeSubscriptionInfoList
for (subscriptionInfo in subscription)
{
val number = subscriptionInfo.number
Log.e("Test", " Number is " + number)
}
Correct way to get IMEI Number KOTLIN
try{
val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val IMEI = tm.getImei()
if (IMEI != null)
Toast.makeText(this, "IMEI number: " + IMEI,
Toast.LENGTH_LONG).show()
}catch (ex:Exception){
Log.e("",ex.message)
}
Including asking for Permission
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_PHONE_STATE)) {
} else { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_PHONE_STATE), 2) } }
Don't forget AndroidManifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Taken from this answer and translated to kotlin:
Getting the Phone Number, IMEI, and SIM Card ID
val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
// For SIM card, use the getSimSerialNumber()
//---get the SIM card ID---
val simID = tm.simSerialNumber
if (simID != null)
Toast.makeText(this, "SIM card ID: " + simID,
Toast.LENGTH_LONG).show()
Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)
//---get the phone number---
val telNumber = tm.line1Number
if (telNumber != null)
Toast.makeText(this, "Phone number: " + telNumber,
Toast.LENGTH_LONG).show()
// IMEI number of the phone, use the getDeviceId()
//---get the IMEI number---
val IMEI = tm.deviceId
if (IMEI != null)
Toast.makeText(this, "IMEI number: " + IMEI,
Toast.LENGTH_LONG).show()
Permissions needed:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Please note that some devices could not return the phone number due to its internal implementation.
Right now you can not access these Info according to docs:
getSerial()
getImei()
getDeviceId()
getMeid()
getSimSerialNumber()
getSubscriberId()
If your app targets Android 10 or higher, a SecurityException occurs.
If your app targets Android 9 (API level 28) or lower, the method returns null or placeholder data if the app has the READ_PHONE_STATE permission. Otherwise, a SecurityException occurs.
I know how to get user's phone number, but let's say the user's phone is dual SIM. Is there any way to get both phone numbers? Currently I am getting the active phone number only.
If the phone number is indeed stored in the SIM card, then you can use subscriptionmanager API (https://developer.android.com/reference/android/telephony/SubscriptionManager.html) to get the details on each subscription i.e for each SIM card.
You can call
getActiveSubscriptionInfoList() which will return list. In your case if there are 2 SIM cards inserted, it should return 2 subscription infos
In subscription info, you can call getNumber() API (https://developer.android.com/reference/android/telephony/SubscriptionInfo.html#getNumber()) to get the number
Please note that for this to work, the SIM card should have the phone number in it.
Please note this API is only supported from API level 22
Adding example code :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
SubscriptionManager subscriptionManager = SubscriptionManager.from(getApplicationContext());
List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();
Log.d("Test", "Current list = " + subsInfoList);
for (SubscriptionInfo subscriptionInfo : subsInfoList) {
String number = subscriptionInfo.getNumber();
Log.d("Test", " Number is " + number);
}
}
I have Kotlinized #manishg code (from 5 years ago):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
val subscriptionManager = SubscriptionManager.from(applicationContext)
val subsInfoList = subscriptionManager.activeSubscriptionInfoList
Log.d("Test", "Current list = $subsInfoList")
for (subscriptionInfo in subsInfoList) {
val number = subscriptionInfo.number
Log.d("Test", " Number is $number")
}
}
Note #1: you must add to the manifest:
uses-permission android:name="android.permission.READ_PHONE_STATE"
Note #2: you should have a permission check on your code, like:
val subsInfoList = if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// ActivityCompat#requestPermissions
return
} else {
//todo return "no permissions"
}
I'm Trying the following code to get System phone number
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number();
But it is not working.
In my phone, i use
Settings->About Phone-->Status-Phone Number
is there a simple app i can use ? , I m writing from Turkey. does sim card make a difference ?
Not all telecom carriers store the phone number on the SIM card. The approach you are using only works if the SIM card in the device has the mobile number stored on it.
If you cannot see your phone number in the mobile settings, then it means that it isn't stored on the SIM card. You will have to manually ask the user to enter it into your app if you absolutely need it. There is no other way.
You can try something like this. It works perfectly.
public String getPhoneNumber(Context context) {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String num = mTelephonyMgr.getLine1Number();
return fillPhoneNumber(num);
}
private String fillPhoneNumber(String num) {
try{
if (num != null && num.length() > 0) {
if (num.length() >= 9) {
num = num.replaceAll("\\D", "");
if (num.substring(0, 1).equals("8")) {
num = "+3" + num;
} else if (num.substring(0, 1).equals("0")) {
num = "+38" + num;
} else if (num.substring(0, 1).equals("3")) {
num = "+" + num;
}
}
return num;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
Note: Not all phones return a phone number.
There is no deterministic way to find the MSISDN. The above approach only works if SIM has stored the MSISDN. Other work around is to retrieve the number from facebook. It also may or may not work.
The only sure shot way is to create account with some SMS gateway provider like http://trumpia.com, then send SMS to the toll free number, and then call the API to retrieve the MSISDN.
To identify each devices uniquely I would like to use the IMEI (or ESN number for CDMA devices). How to access this programmatically?
You want to call android.telephony.TelephonyManager.getDeviceId().
This will return whatever string uniquely identifies the device (IMEI on GSM, MEID for CDMA).
You'll need the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
in order to do this.
That being said, be careful about doing this. Not only will users wonder why your application is accessing their telephony stack, it might be difficult to migrate data over if the user gets a new device.
Update: As mentioned in the comments below, this is not a secure way to authenticate users, and raises privacy concerns. It is not recommended. Instead, look at the Google+ Login API if you want to implement a frictionless login system.
The Android Backup API is also available if you just want a lightweight way to persist a bundle of strings for when a user resets their phone (or buys a new device).
In addition to the answer of Trevor Johns, you can use this as follows:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
And you should add the following permission into your Manifest.xml file:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
In emulator, you'll probably get a like a "00000..." value. getDeviceId() returns NULL if device ID is not available.
I use the following code to get the IMEI or use Secure.ANDROID_ID as an alternative, when the device doesn't have phone capabilities:
/**
* Returns the unique identifier for the device
*
* #return unique identifier for the device
*/
public String getDeviceIMEI() {
String deviceUniqueIdentifier = null;
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (null != tm) {
deviceUniqueIdentifier = tm.getDeviceId();
}
if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
return deviceUniqueIdentifier;
}
Or you can use the ANDROID_ID setting from Android.Provider.Settings.System (as described here strazerre.com).
This has the advantage that it doesn't require special permissions but can change if another application has write access and changes it (which is apparently unusual but not impossible).
Just for reference here is the code from the blog:
import android.provider.Settings;
import android.provider.Settings.System;
String androidID = System.getString(this.getContentResolver(),Secure.ANDROID_ID);
Implementation note: if the ID is critical to the system architecture you need to be aware that in practice some of the very low end Android phones & tablets have been found reusing the same ANDROID_ID (9774d56d682e549c was the value showing up in our logs)
From: http://mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/:
The following code helps in obtaining IMEI number of android devices :
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
Permissions required in Android Manifest:
android.permission.READ_PHONE_STATE
NOTE: In case of tablets or devices which can’t act as Mobile Phone
IMEI will be null.
to get IMEI (international mobile equipment identifier)
public String getIMEI(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
to get device unique id
public String getDeviceUniqueID(Activity activity){
String device_unique_id = Secure.getString(activity.getContentResolver(),
Secure.ANDROID_ID);
return device_unique_id;
}
For Android 6.0+ the game has changed so i suggest you use this;
The best way to go is during runtime else you get permission errors.
/**
* A loading screen after AppIntroActivity.
*/
public class LoadingActivity extends BaseActivity {
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private TextView loading_tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
//trigger 'loadIMEI'
loadIMEI();
/** Fading Transition Effect */
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
/**
* Called when the 'loadIMEI' function is triggered.
*/
public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestReadPhoneStatePermission();
} else {
// READ_PHONE_STATE permission is already been granted.
doPermissionGrantedStuffs();
}
}
/**
* Requests the READ_PHONE_STATE permission.
* If the permission has been denied previously, a dialog will prompt the user to grant the
* permission, otherwise it is requested directly.
*/
private void requestReadPhoneStatePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
new AlertDialog.Builder(LoadingActivity.this)
.setTitle("Permission Request")
.setMessage(getString(R.string.permission_read_phone_state_rationale))
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//re-request
ActivityCompat.requestPermissions(LoadingActivity.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
})
.setIcon(R.drawable.onlinlinew_warning_sign)
.show();
} else {
// READ_PHONE_STATE permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
// Received permission result for READ_PHONE_STATE permission.est.");
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number
//alertAlert(getString(R.string.permision_available_read_phone_state));
doPermissionGrantedStuffs();
} else {
alertAlert(getString(R.string.permissions_not_granted_read_phone_state));
}
}
}
private void alertAlert(String msg) {
new AlertDialog.Builder(LoadingActivity.this)
.setTitle("Permission Request")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do somthing here
}
})
.setIcon(R.drawable.onlinlinew_warning_sign)
.show();
}
public void doPermissionGrantedStuffs() {
//Have an object of TelephonyManager
TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
//Get IMEI Number of Phone //////////////// for this example i only need the IMEI
String IMEINumber=tm.getDeviceId();
/************************************************
* **********************************************
* This is just an icing on the cake
* the following are other children of TELEPHONY_SERVICE
*
//Get Subscriber ID
String subscriberID=tm.getDeviceId();
//Get SIM Serial Number
String SIMSerialNumber=tm.getSimSerialNumber();
//Get Network Country ISO Code
String networkCountryISO=tm.getNetworkCountryIso();
//Get SIM Country ISO Code
String SIMCountryISO=tm.getSimCountryIso();
//Get the device software version
String softwareVersion=tm.getDeviceSoftwareVersion()
//Get the Voice mail number
String voiceMailNumber=tm.getVoiceMailNumber();
//Get the Phone Type CDMA/GSM/NONE
int phoneType=tm.getPhoneType();
switch (phoneType)
{
case (TelephonyManager.PHONE_TYPE_CDMA):
// your code
break;
case (TelephonyManager.PHONE_TYPE_GSM)
// your code
break;
case (TelephonyManager.PHONE_TYPE_NONE):
// your code
break;
}
//Find whether the Phone is in Roaming, returns true if in roaming
boolean isRoaming=tm.isNetworkRoaming();
if(isRoaming)
phoneDetails+="\nIs In Roaming : "+"YES";
else
phoneDetails+="\nIs In Roaming : "+"NO";
//Get the SIM state
int SIMState=tm.getSimState();
switch(SIMState)
{
case TelephonyManager.SIM_STATE_ABSENT :
// your code
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
// your code
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED :
// your code
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED :
// your code
break;
case TelephonyManager.SIM_STATE_READY :
// your code
break;
case TelephonyManager.SIM_STATE_UNKNOWN :
// your code
break;
}
*/
// Now read the desired content to a textview.
loading_tv2 = (TextView) findViewById(R.id.loading_tv2);
loading_tv2.setText(IMEINumber);
}
}
Hope this helps you or someone.
As in API 26 getDeviceId() is depreciated so you can use following code to cater API 26 and earlier versions
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei="";
if (android.os.Build.VERSION.SDK_INT >= 26) {
imei=telephonyManager.getImei();
}
else
{
imei=telephonyManager.getDeviceId();
}
Don't forget to add permission requests for READ_PHONE_STATE to use the above code.
UPDATE:
From Android 10 its is restricted for user apps to get non-resettable hardware identifiers like IMEI.
New Update:
For Android Version 6 And Above, WLAN MAC Address has been deprecated , follow Trevor Johns answer
Update:
For uniquely Identification of devices, You can Use Secure.ANDROID_ID.
Old Answer:
Disadvantages of using IMEI as Unique Device ID:
IMEI is dependent on the Simcard slot of the device, so it is not
possible to get the IMEI for the devices that do not use Simcard.
In Dual sim devices, we get 2 different IMEIs for the same device as it has 2 slots for simcard.
You can Use The WLAN MAC Address string (Not Recommended For Marshmallow and Marshmallow+ as WLAN MAC Address has been deprecated on Marshmallow forward. So you'll get a bogus value)
We can get the Unique ID for android phones using the WLAN MAC address also. The MAC address is unique for all devices and it works for all kinds of devices.
Advantages of using WLAN MAC address as Device ID:
It is unique identifier for all type of devices (smart phones and
tablets).
It remains unique if the application is reinstalled
Disadvantages of using WLAN MAC address as Device ID:
Give You a Bogus Value from Marshmallow and above.
If device doesn’t have wifi hardware then you get null MAC address,
but generally it is seen that most of the Android devices have wifi
hardware and there are hardly few devices in the market with no wifi
hardware.
SOURCE : technetexperts.com
The method getDeviceId() of TelephonyManager returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.
Java Code
package com.AndroidTelephonyManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textDeviceID = (TextView)findViewById(R.id.deviceid);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(telephonyManager));
}
String getDeviceID(TelephonyManager phonyManager){
String id = phonyManager.getDeviceId();
if (id == null){
id = "not available";
}
int phoneType = phonyManager.getPhoneType();
switch(phoneType){
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE: " + id;
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM: IMEI=" + id;
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA: MEID/ESN=" + id;
/*
* for API Level 11 or above
* case TelephonyManager.PHONE_TYPE_SIP:
* return "SIP";
*/
default:
return "UNKNOWN: ID=" + id;
}
}
}
XML
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="#string/hello">
<textview android:id="#+id/deviceid" android:layout_height="wrap_content" android:layout_width="fill_parent">
</textview></textview></linearlayout>
Permission Required
READ_PHONE_STATE in manifest file.
You can use this TelephonyManager TELEPHONY_SERVICE function to get unique device ID,
Requires Permission: READ_PHONE_STATE
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Example, the IMEI for GSM and the MEID or ESN for CDMA phones.
/**
* Gets the device unique id called IMEI. Sometimes, this returns 00000000000000000 for the
* rooted devices.
**/
public static String getDeviceImei(Context ctx) {
TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
Return null if device ID is not available.
Try this(need to get first IMEI always)
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(LoginActivity.this,Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (mTelephony.getPhoneCount() == 2) {
IME = mTelephony.getImei(0);
}else{
IME = mTelephony.getImei();
}
}else{
if (mTelephony.getPhoneCount() == 2) {
IME = mTelephony.getDeviceId(0);
} else {
IME = mTelephony.getDeviceId();
}
}
} else {
IME = mTelephony.getDeviceId();
}
Use below code gives you IMEI number:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
System.out.println("IMEI::" + telephonyManager.getDeviceId());
The method getDeviceId() is deprecated.
There a new method for this getImei(int)
Check here
You'll need the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
To get IMEI (international mobile equipment identifier) and if It is above API level 26 then we get telephonyManager.getImei() as null so for that, we use ANDROID_ID as a Unique Identifier.
public static String getIMEINumber(#NonNull final Context context)
throws SecurityException, NullPointerException {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
assert tm != null;
imei = tm.getImei();
//this change is for Android 10 as per security concern it will not provide the imei number.
if (imei == null) {
imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
} else {
assert tm != null;
if (tm.getDeviceId() != null && !tm.getDeviceId().equals("000000000000000")) {
imei = tm.getDeviceId();
} else {
imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
return imei;
}
For Android 10 Following code is working for me.
val uid: String = Settings.Secure.getString(ctx.applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
imei = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
uid
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
telephonyManager.imei
}
else -> {
telephonyManager.deviceId
}
}
}
for API Level 11 or above:
case TelephonyManager.PHONE_TYPE_SIP:
return "SIP";
TelephonyManager tm= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(tm));
Kotlin Code for getting DeviceId ( IMEI ) with handling permission & comparability check for all android versions :
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is granted
val imei : String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) telephonyManager.imei
// older OS versions
else telephonyManager.deviceId
imei?.let {
Log.i("Log", "DeviceId=$it" )
}
} else { // Permission is not granted
}
Also add this permission to AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->
use below code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = {Manifest.permission.READ_PHONE_STATE};
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, READ_PHONE_STATE);
}
} else {
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
And call onRequestPermissionsResult method following code:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case READ_PHONE_STATE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Add following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
For those looking for a Kotlin version, you can use something like this;
private fun telephonyService() {
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
val imei = if (android.os.Build.VERSION.SDK_INT >= 26) {
Timber.i("Phone >= 26 IMEI")
telephonyManager.imei
} else {
Timber.i("Phone IMEI < 26")
telephonyManager.deviceId
}
Timber.i("Phone IMEI $imei")
}
NOTE: You must wrap telephonyService() above with a permission check using checkSelfPermission or whatever method you use.
Also add this permission in the manifest file;
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
There is no Way you can get imei number from andorid 10+ or 29+ mobiles here is the alternative function that will be used for creating imei number for devices.
public static String getDeviceID(){
String devIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length()%10+ Build.BRAND.length()%10 +
Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
Build.TAGS.length()%10 + Build.TYPE.length()%10 +
Build.USER.length()%10 ; //13 digits
return devIDShort;
}
Restriction on non-resettable device identifiers
Starting in Android 10, apps must have the READ_PRIVILEGED_PHONE_STATE privileged permission in order to access the device's non-resettable identifiers, which include both IMEI and serial number.