【转】Android中关于Deviceid的那些事

转载自:Android中关于Deviceid的那些事


Android 中获取设备id一直是老生常谈的事情,先说下名词解释

    • Device ID:设备ID。
    • IMEI:International Mobile Equipment Identity,国际移动设备身份码的缩写。是由15位数字组成的“电子串号”,它与每台手机一一对应,每个IMEI在世界上都是唯一的。
    • IDFA:Identifier For Advertising,iOS独有的广告标识符。
    • UDID:Unique Device Identifier,唯一设备标识码。
    • UUID:Universally Unique Identifier,通用唯一识别码。目前最广泛应用的UUID,是微软公司的全局唯一标识符GUID。其目的是让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要通过中央控制端来做辨识信息的指定。
    • ANDROID_ID:在 Android 8.0(API 级别 26)和更高版本的平台上,一个 64 位数字(表示为十六进制字符串),对于应用签名密钥、用户和设备的每个组合都是唯一的值。

今天我们先说一下获取deviceId的方法:

/**
 * 获取deviceId(手机唯一的标识)
 *
 * @param context
 * @return
 */
@SuppressLint({"HardwareIds"})
public static String getDeviceId(Context context) {
    String deviceId;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    } else {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        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);
        }
    }
    return deviceId;
}

发表评论