How to get the Android device ID with TelephonyManager # getDeviceId ()?

3

I'm using this code to get the ID of the Android device.

TelephonyManager telephonyManager = (TelephonyManager) getActivity().getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
id = telephonyManager.getDeviceId();

But now I noticed that in some cases, ID was written as null .

  • I'm not sure about getting ID this way?
  • Under what circumstances does this return null?
asked by anonymous 13.04.2017 / 22:04

2 answers

4
  

Am I not sure about getting the ID that way?

Not for the purpose you want. TelephonyManager # getDeviceId () returns the IMEI from a phone GSM or the MEID or ESN of phones < a href="https://en.wikipedia.org/wiki/Code-division_multiple_access"> CDMA . Not all Android devices are phones.

  

In what circumstances does this return null?

When the device is not a phone. (How to know if your device is a Smathphone or Tablet and / or if you are able to send SMS?)

    
13.04.2017 / 22:17
3

The getDeviceId() returns only value when the device is considering a phone.

If you want to get a "unique" identifier from the device you can use Secure.ANDROID_ID . Here's an example:

import android.provider.Settings.Secure;
private String android_id = Secure.getString(
    getContext().getContentResolver(), Secure.ANDROID_ID);

However, you should be careful because you can edit the device's factory settings, for example by changing this setting.

In Best Practices for Unique Identifiers reads as follows :

  

1: Avoid using hardware identifiers. Hardware identifiers such as SSAID (Android code) and IMEI can be avoided   in most use cases without limiting the resources needed.

    
13.04.2017 / 22:24