如何在应用程序中获取Android手机的UUID?

60
我正在寻求帮助来获取我Android手机的UUID。我已经在网络上搜索并找到了一个潜在的解决方案,但它在模拟器中无法正常工作。
以下是代码:

我正在寻求帮助来获取我Android手机的UUID。我已经在网络上搜索并找到了一个潜在的解决方案,但它在模拟器中无法正常工作。

以下是代码:

Class<?> c;
try {
    c = Class.forName("android.os.SystemProperties");
    Method get = c.getMethod("get", String.class);
    serial = (String) get.invoke(c, "ro.serialno");
    Log.d("ANDROID UUID",serial);
} catch (Exception e) {
    e.printStackTrace();
}

有人知道为什么它不工作,或者有更好的解决方案吗?


请查看此帖子 https://dev59.com/rW855IYBdhLWcg3wNxgM - Mudassir
1
@Mudassir Thaks。我看了一下,有很多答案可以回答你的问题,但是哪一个最为乐观呢?我还找到了一种解决方案,可以基于主机名、MAC地址、操作系统名称和版本生成唯一的UUID。但是如何获取内置的UUID呢? - bHaRaTh
谢谢Zelimir,您消除了我的疑惑。因此我将使用UUID生成算法来生成一个UUID,这应该足够了,对吧? - bHaRaTh
是的,您可以确信它是独一无二的。 - Zelimir
1
我注意到在一个安装了Gingerbread的Nexus-One上,ro.serialnoandroid.os.Build.SERIAL是相同的。 - Martin
显示剩余2条评论
8个回答

104
作为Dave Webb提到的,Android开发者博客有一篇文章涵盖了这个问题。他们首选的解决方案是跟踪应用程序安装而不是设备,这对大多数情况都非常有效。这篇博客将展示您需要的代码,让它起作用,并且我建议您查看它。
然而,博客文章继续讨论了如果需要设备标识符而不是应用程序安装标识符的解决方案。我与Google的某位人员交谈,以获取有关某些项目的额外澄清,以防您需要这样做。以下是我在上述博客文章中未提到的有关设备标识符的发现:
  • ANDROID_ID是首选的设备标识符。在Android版本<=2.1或>=2.3上,ANDROID_ID非常可靠。仅2.2存在帖子中提到的问题。
  • 多个制造商的几款设备受到2.2中ANDROID_ID漏洞的影响。
  • 据我所知,所有受影响的设备都有相同的ANDROID_ID,即9774d56d682e549c。顺便说一下,模拟器报告的设备ID也是相同的。
  • 谷歌认为OEM已经为许多或大多数设备修补了这个问题,但我能够验证至少在2011年4月初,仍然很容易找到具有破损ANDROID_ID的设备。
  • 当设备有多个用户(适用于运行Android 4.2或更高版本的某些设备)时,每个用户都会显示为完全独立的设备,因此ANDROID_ID值对每个用户都是唯一的。
根据Google的建议,我实现了一个类,用于生成唯一的设备UUID,使用ANDROID_ID作为种子(如果适用),必要时回退到TelephonyManager.getDeviceId(),如果失败,则使用随机生成的唯一UUID,在应用程序重新启动时保持不变(但不包括应用程序重新安装)。
请注意,对于需要回退到设备ID的设备,唯一ID将在恢复出厂设置后保持不变。这是需要注意的事项。如果您需要确保恢复出厂设置会重置您的唯一ID,则可能需要考虑直接回退到随机UUID而不是设备ID。
再次说明,此代码用于设备ID,而不是应用程序安装ID。对于大多数情况,应用程序安装ID可能是您要查找的内容。但是,如果您确实需要设备ID,则以下代码可能适合您。
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class DeviceUuidFactory {
    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";

    protected static UUID uuid;



    public DeviceUuidFactory(Context context) {

        if( uuid ==null ) {
            synchronized (DeviceUuidFactory.class) {
                if( uuid == null) {
                    final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
                    final String id = prefs.getString(PREFS_DEVICE_ID, null );

                    if (id != null) {
                        // Use the ids previously computed and stored in the prefs file
                        uuid = UUID.fromString(id);

                    } else {

                        final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

                        // Use the Android ID unless it's broken, in which case fallback on deviceId,
                        // unless it's not available, then fallback on a random number which we store
                        // to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                            } else {
                                final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                                uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }

                        // Write the value out to the prefs file
                        prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();

                    }

                }
            }
        }

    }


    /**
     * Returns a unique UUID for the current android device.  As with all UUIDs, this unique ID is "very highly likely"
     * to be unique across all Android devices.  Much more so than ANDROID_ID is.
     *
     * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
     * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
     * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
     * usable value.
     *
     * In some rare circumstances, this ID may change.  In particular, if the device is factory reset a new device ID
     * may be generated.  In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
     * to a newer, non-buggy version of Android, the device ID may change.  Or, if a user uninstalls your app on
     * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
     *
     * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
     * change after a factory reset.  Something to be aware of.
     *
     * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
     *
     * @see http://code.google.com/p/android/issues/detail?id=10603
     *
     * @return a UUID that may be used to uniquely identify your device for most purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }
}

1
  1. 为什么要使用Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);,而不是直接从Secure.ANDROID_ID访问常量?
  2. 我们不能使用UUID.fromString(ANDROID_ID)代替getBytes("utf8")吗?
- alkber
你为什么选择不将这段代码发布到GitHub或类似的平台上,这样分享和维护都会更加容易呢? - AWrightIV
@AWrightIV 答案应该是自包含的,链接到 Github 恰恰相反。 - Michael Mrozek
Android Studio 3.1.3 创建了一个警告,告诉我们不要使用 getString()。这篇文章仍然非常有用,但我想它可能已经过时了? - JamisonMan111

67

这对我很有效:

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();

编辑:

你还需要在你的清单文件中设置 android.permission.READ_PHONE_STATE。自 Android M 以来,你需要在运行时请求此权限。

请参阅这个答案:https://dev59.com/EVwY5IYBdhLWcg3wVGiB#38782876


8
因为您正在模拟器上测试。 - Zelimir
1
是的,Zelimir,我在设备上测试过了,它运行得很好。非常感谢您的帮助。 - bHaRaTh
46
请注意,这只适用于手机。没有电话功能的设备(如平板电脑)将无法使用此功能。 - Michał Klimczak
7
但这个可以在平板电脑上使用。http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID - outlying
12
这里所提到的不是UUID,而是IMEI,把它称为UUID会让那些将其视为UUID的人感到困惑。请注意不改变原意。 - sivi
显示剩余4条评论

9

不要从TelephonyManager获取IMEI,而是使用ANDROID_ID。

Settings.Secure.ANDROID_ID

无论是否有电话功能,此方法适用于所有安卓设备。

8

这是正确的答案。不需要清单权限。 - Avi Levin
19
问题是获取设备 UUID,而不是随机生成一个。 - Juan Saravia

7
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

4

从API 26开始,getDeviceId()已被弃用。如果您需要获取设备的IMEI,请使用以下方法:

 String deviceId = "";
    if (Build.VERSION.SDK_INT >= 26) {
        deviceId = getSystemService(TelephonyManager.class).getImei();
    }else{
        deviceId = getSystemService(TelephonyManager.class).getDeviceId();
    }

这需要权限“android.permission.READ_PRIVILEGED_PHONE_STATE”。从Android 10开始,您不能将此权限放在清单中。“READ_PRIVILEGED_PHONE_STATE权限仅授予使用平台密钥和特权系统应用程序签名的应用程序。”-> source.android.com/docs/core/connect/device-identifiers因此,从Android 10开始,这将无法工作。 - Ajji

1
添加
  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

方法

String getUUID(){
    TelephonyManager teleManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String tmSerial = teleManager.getSimSerialNumber();
    String tmDeviceId = teleManager.getDeviceId();
    String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
    if (tmSerial  == null) tmSerial   = "1";
    if (tmDeviceId== null) tmDeviceId = "1";
    if (androidId == null) androidId  = "1";
    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDeviceId.hashCode() << 32) | tmSerial.hashCode());
    String uniqueId = deviceUuid.toString();
    return uniqueId;
}

工作得很好,备用方案不错。由于我是Android编程的新手,在页面上请求Manifest.permission.READ_PHONE_STATE之前它对我不起作用。 - deebs
感谢您的建议,这是一个补充。 - KongJing

0

我认为你可以使用ANDROID_ID技术上生成一个唯一的标识,类似于:

UUID.nameUUIDFromBytes(Settings.Secure.ANDROID_ID.encodeToByteArray()).toString()

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接