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

发布于 2024-10-19 07:25:56 字数 407 浏览 3 评论 0原文

我正在寻求帮助来获取 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();
}

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

I'm looking for help to get the UUID of my Android phone. I have searched the net and found one potential solution but it is not working in the emulator.

Here is the code:

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();
}

Does anybody know why it isn't working, or have a better solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

对你的占有欲 2024-10-26 07:25:56

正如 Dave Webb 提到的,Android 开发者博客有一篇文章 涵盖了这一点。他们首选的解决方案是跟踪应用程序安装而不是设备,这对于大多数用例都适用。这篇博客文章将向您展示实现该功能所需的代码,我建议您查看一下。

但是,如果您需要设备标识符而不是应用程序安装标识符,该博客文章继续讨论解决方案。我与 Google 的某人进行了交谈,以便在您需要时对一些项目进行一些额外的说明。以下是我在上述博客文章中未提及的有关设备标识符的发现:

  • ANDROID_ID 是首选设备标识符。 ANDROID_ID 在 Android <=2.1 或 >=2.3 版本上完全可靠。只有2.2有帖子中提到的问题。
  • 多个制造商的多个设备受到 2.2 中 ANDROID_ID 错误的影响。
  • 据我所知,所有受影响的设备都相同ANDROID_ID,即 9774d56d682e549c 。顺便说一句,这也是模拟器报告的相同设备 ID。
  • Google 相信 OEM 厂商已经为他们的许多或大部分设备修复了这个问题,但我能够证实,至少截至 2011 年 4 月上旬,仍然很容易找到 ANDROID_ID 损坏的设备。
  • 当设备有多个用户时 (在运行 Android 4.2 或 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;
    }
}

As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.

However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:

  • ANDROID_ID is the preferred device identifier. ANDROID_ID is perfectly reliable on versions of Android <=2.1 or >=2.3. Only 2.2 has the problems mentioned in the post.
  • Several devices by several manufacturers are affected by the ANDROID_ID bug in 2.2.
  • As far as I've been able to determine, all affected devices have the same ANDROID_ID, which is 9774d56d682e549c. Which is also the same device id reported by the emulator, btw.
  • Google believes that OEMs have patched the issue for many or most of their devices, but I was able to verify that as of the beginning of April 2011, at least, it's still quite easy to find devices that have the broken ANDROID_ID.
  • When a device has multiple users (available on certain devices running Android 4.2 or higher), each user appears as a completely separate device, so the ANDROID_ID value is unique to each user.

Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).

Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.

Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.

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;
    }
}
未蓝澄海的烟 2024-10-26 07:25:56

这对我有用:

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

编辑:

您还需要在清单中设置android.permission.READ_PHONE_STATE。从 Android M 开始,您需要在运行时请求此权限。

请参阅此答案:https://stackoverflow.com/a/38782876/1339179

This works for me:

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

EDIT :

You also need android.permission.READ_PHONE_STATE set in your Manifest. Since Android M, you need to ask this permission at runtime.

See this anwser : https://stackoverflow.com/a/38782876/1339179

逆光下的微笑 2024-10-26 07:25:56

使用 ANDROID_ID 代替从 TelephonyManager 获取 IMEI。

Settings.Secure.ANDROID_ID

这适用于每个 Android 设备,无论是否有电话功能。

Instead of getting IMEI from TelephonyManager use ANDROID_ID.

Settings.Secure.ANDROID_ID

This works for each android device irrespective of having telephony.

无所谓啦 2024-10-26 07:25:56
 String id = UUID.randomUUID().toString();

请参阅 Android 开发者博客文章,了解如何使用 UUID 类获取 uuid

 String id = UUID.randomUUID().toString();

See Android Developer blog article for using UUID class to get uuid

2024-10-26 07:25:56
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
忆悲凉 2024-10-26 07:25:56

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

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

As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:

 String deviceId = "";
    if (Build.VERSION.SDK_INT >= 26) {
        deviceId = getSystemService(TelephonyManager.class).getImei();
    }else{
        deviceId = getSystemService(TelephonyManager.class).getDeviceId();
    }
漆黑的白昼 2024-10-26 07:25:56

添加

  <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;
}

Add

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

Method

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;
}
岁月无声 2024-10-26 07:25:56

我认为您可以在技术上使用 ANDROID_ID 生成一个唯一的 ID,例如:

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

I think you can technically generate a unique one using the ANDROID_ID, something like:

UUID.nameUUIDFromBytes(Settings.Secure.ANDROID_ID.encodeToByteArray()).toString()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文