Android 设备是否有唯一 ID,如果有,使用 Java 访问它的简单方法是什么?
Settings.Secure#ANDROID_ID
将 Android ID 作为 unique for each user 64 位十六进制字符串返回。
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
另请阅读唯一标识符的最佳做法:https://developer.android.com/training/articles/user-data-ids
更新:在最近的 Android 版本中,许多与 ANDROID_ID
相关的问题都已解决,我相信这种方法不再需要。请看一下Anthony's answer。
完全披露:我的应用程序最初使用了以下方法,但不再使用这种方法,我们现在使用 emmby's answer 链接到的 Android Developer Blog 条目中概述的方法(即生成和保存 UUID#randomUUID()
)。
这个问题有很多答案,其中大多数只能在“某些”时间里起作用,不幸的是,这还不够好。
根据我对设备的测试(所有手机,至少其中一部未激活):
所有测试的设备都返回了 TelephonyManager.getDeviceId() 的值 所有 GSM 设备(所有测试都使用 SIM 卡)返回了 TelephonyManager.getSimSerialNumber() 的值 所有 CDMA 设备都返回了 getSimSerialNumber() 的值(如预期的那样) 所有具有 Google 帐户的设备added 返回了 ANDROID_ID 的值 所有 CDMA 设备都为 ANDROID_ID 和 TelephonyManager.getDeviceId() 返回了相同的值(或相同值的派生)——只要在设置期间添加了 Google 帐户。我还没有机会测试没有 SIM 卡的 GSM 设备、没有添加 Google 帐户的 GSM 设备或任何处于飞行模式的设备。
因此,如果您想要设备本身独有的东西,TM.getDeviceId()
应该就足够了。显然,有些用户比其他用户更偏执,因此对这些标识符中的 1 个或多个进行哈希处理可能很有用,这样字符串对于设备实际上仍然是唯一的,但不会明确标识用户的实际设备。例如,使用 String.hashCode()
,结合 UUID:
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
String deviceId = deviceUuid.toString();
可能会导致类似:00000000-54b3-e7c7-0000-000046bffd97
它对我来说足够好。
正如 Richard 在下面提到的,不要忘记您需要读取 TelephonyManager
属性的权限,因此请将其添加到您的清单中:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
导入库
import android.content.Context;
import android.telephony.TelephonyManager;
import android.view.View;
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
添加到清单文件。如果存储在数据库中,则返回的字符串长度为 36 个字符。
#最后更新时间:2015 年 6 月 2 日
在阅读了有关创建唯一 ID 的每篇 Stack Overflow 帖子、Google 开发人员博客和 Android 文档之后,我觉得“伪 ID”似乎是最好的选择。
主要问题:硬件与软件
硬件
用户可以更改他们的硬件、Android 平板电脑或手机,因此基于硬件的唯一 ID 不是跟踪用户的好主意
对于跟踪硬件,这是个好主意
软件
用户可以擦除/更改他们的 ROM,如果他们是 root
您可以跨平台(iOS、Android、Windows 和 Web)跟踪用户
在征得他们同意的情况下跟踪个人用户的最佳方法是让他们登录(使用 OAuth 无缝连接)
#Android的整体故障
###- 保证 API >= 9/10(99.5% 的 Android 设备)的唯一性(包括根设备)###- 没有额外的权限
伪代码:
if API >= 9/10: (99.5% of devices)
return unique ID containing serial id (rooted devices may be different)
else
return the unique ID of build information (may overlap data - API < 9)
感谢 @stansult 发布 all of our options(在此 Stack Overflow 问题中)。
##选项列表 - 为什么/为什么不使用它们的原因:
用户电子邮件 - 软件
用户可以更改电子邮件 - 极不可能
API 5+
API 14+
用户电话号码 - 软件
用户可以更改电话号码 - 极不可能
IMEI - 硬件(仅限手机,需要 android.permission.READ_PHONE_STATE)
大多数用户讨厌它在权限中显示“电话呼叫”这一事实。一些用户给出不好的评价是因为他们认为您只是在窃取他们的个人信息,而您真正想要做的只是跟踪设备安装。很明显,您正在收集数据。
Android ID - 硬件(可以为空,可以在出厂重置时更改,可以在有根设备上更改)
因为它可以是'null',我们可以检查'null'并改变它的值,但这意味着它不再是唯一的。
如果您的用户使用恢复出厂设置的设备,则该值可能已在根设备上更改或更改,因此如果您正在跟踪用户安装,则可能存在重复条目。
WLAN MAC 地址 - 硬件(需要 android.permission.ACCESS_WIFI_STATE)
这可能是次优选择,但您仍在收集和存储直接来自用户的唯一标识符。很明显,您正在收集数据。
蓝牙 MAC 地址 - 硬件(带蓝牙的设备,需要 android.permission.BLUETOOTH)
市场上的大多数应用程序不使用蓝牙,因此如果您的应用程序不使用蓝牙并且您包含蓝牙,用户可能会产生怀疑。
伪唯一 ID - 软件(适用于所有 Android 设备)
很有可能,可能包含冲突 - 请参阅下面发布的我的方法!
这使您可以从用户那里获得一个“几乎唯一”的 ID,而无需获取任何私人信息。您可以根据设备信息创建自己的匿名 ID。
我知道没有任何“完美”的方法可以在不使用权限的情况下获取唯一 ID。但是,有时我们只需要跟踪设备安装。在创建唯一 ID 时,我们可以仅根据 Android API 提供给我们的信息创建一个“伪唯一 ID”,而无需使用额外的权限。这样,我们可以向用户表示尊重,并尝试提供良好的用户体验。
使用伪唯一 ID,您实际上只会遇到这样一个事实,即基于存在类似设备的事实可能存在重复。您可以调整组合方法以使其更加独特;但是,一些开发人员需要跟踪设备安装,这将基于类似设备实现技巧或性能。
##API >= 9:
如果他们的 Android 设备是 API 9 或更高版本,则由于“Build.SERIAL”字段,这保证是唯一的。
记住,从技术上讲,您只错过了大约 0.5% 的用户who have API < 9。所以你可以专注于其余的:这是 99.5% 的用户!
##API < 9:
如果用户的Android设备低于API 9;希望他们没有进行出厂重置,并且他们的“Secure.ANDROID_ID”将被保留或不为“null”。 (见http://developer.android.com/about/dashboards/index.html)
##如果一切都失败了:
如果一切都失败了,如果用户确实低于 API 9(低于 Gingerbread),重置了他们的设备,或者“Secure.ANDROID_ID”返回“null”,那么返回的 ID 将完全基于他们的 Android 设备信息.这是可能发生碰撞的地方。
变化:
删除了“Android.SECURE_ID”,因为出厂重置可能会导致值更改
编辑代码以更改 API
改变了伪
请看下面的方法:
/**
* Return pseudo unique ID
* @return ID
*/
public static String getUniquePsuedoID() {
// If all else fails, if the user does have lower than API 9 (lower
// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'
// returns 'null', then simply the ID returned will be solely based
// off their Android device information. This is where the collisions
// can happen.
// Thanks http://www.pocketmagic.net/?p=1662!
// Try not to use DISPLAY, HOST or ID - these items could change.
// If there are collisions, there will be overlapping data
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to @Roman SL!
// https://stackoverflow.com/a/4789483/950427
// Only devices with API >= 9 have android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// If a user upgrades software or roots their device, there will be a duplicate entry
String serial = null;
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception exception) {
// String needs to be initialized
serial = "serial"; // some value
}
// Thanks @Joe!
// https://stackoverflow.com/a/2853253/950427
// Finally, combine the values we have found by using the UUID class to create a unique identifier
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
#New(适用于带有广告和 Google Play 服务的应用):
从 Google Play 开发者控制台:
自 2014 年 8 月 1 日起,Google Play 开发者计划政策要求上传和更新全新的应用程序以使用广告 ID 代替任何其他持久性标识符用于任何广告目的。学到更多
执行:
允许:
<uses-permission android:name="android.permission.INTERNET" />
代码:
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.google.android.gms.common.GooglePlayServicesAvailabilityException;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import java.io.IOException;
...
// Do not call this function from the main thread. Otherwise,
// an IllegalStateException will be thrown.
public void getIdThread() {
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException exception) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesAvailabilityException exception) {
// Encountered a recoverable error connecting to Google Play services.
} catch (GooglePlayServicesNotAvailableException exception) {
// Google Play services is not available entirely.
}
final String id = adInfo.getId();
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
}
来源/文档:
http://developer.android.com/google/play-services/id.html http://developer.android.com/reference/com/google/android/gms/ads/identifier/AdvertisingIdClient.html
##重要的:
当 Google Play 服务可用时,广告 ID 旨在完全取代现有的其他标识符用于广告目的(例如在 Settings.Secure 中使用 ANDROID_ID)。 Google Play 服务不可用的情况由 getAdvertisingIdInfo() 引发的 GooglePlayServicesNotAvailableException 指示。
##警告,用户可以重置:
http://en.kioskea.net/faq/34732-android-reset-your-advertising-id
我试图引用我从中获取信息的每个链接。如果您缺少并且需要包括在内,请发表评论!
Google 播放器服务实例 ID
https://developers.google.com/instance-id/
正如 Dave Webb 所提到的,Android Developer Blog has an article 涵盖了这一点。他们首选的解决方案是跟踪应用安装而不是设备,这适用于大多数用例。博客文章将向您展示实现该功能所需的代码,我建议您查看一下。
但是,如果您需要设备标识符而不是应用程序安装标识符,博客文章会继续讨论解决方案。如果您需要这样做,我与 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 损坏的设备。
根据 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 volatile 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;
}
}
以下是 Reto Meier 在今年的 Google I/O 演示中使用的代码,用于获取用户的唯一 ID:
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
public synchronized static String id(Context context) {
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(
PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
}
}
return uniqueID;
}
如果您将此与备份策略相结合以将首选项发送到云(也在 Reto 的 talk 中描述,您应该有一个与用户相关联的 ID,并在设备被擦除甚至更换后仍然存在。我计划在未来的分析中使用它(换句话说,我还没有这样做:)。
这是一个简单的问题,没有简单的答案。
此外,这里所有现有的答案要么已过时,要么不可靠。
因此,如果您正在寻找 2020 年后的解决方案。
这里有几件事要记住:
所有基于硬件的标识符(IMEI、MAC、序列号等)对于非 Google 设备(Pixel 和 Nexus 除外)都是不可靠的,这些设备在统计上是 most of the android active devices worldwide。因此官方Android identifiers best practices明确指出:
避免使用硬件标识符,例如 IMEI、MAC 地址等...
这使得这里的大多数答案都无效。同样由于不同的android安全更新,其中一些需要更新和更严格的运行时权限,用户可以简单地拒绝。
例如 CVE-2018-9489
会影响上述所有基于 WIFI 的技术。
这使得这些标识符不仅不可靠,而且在许多情况下也无法访问。
所以用更简单的话来说:不要使用那些技术。
这里的许多其他答案都建议使用 AdvertisingIdClient
,这也是不兼容的,因为它的设计仅用于广告分析。 official reference 中也有说明
仅将广告 ID 用于用户分析或广告用例
它不仅对设备识别不可靠,而且您还必须遵守 user privacy regarding ad tracking 政策,该政策明确规定用户可以随时重置或阻止它。
所以也不要使用它。
由于您无法拥有所需的静态全局唯一且可靠的设备标识符。 Android的官方参考建议:
尽可能为所有其他用例使用 Firebase 安装 ID (FID) 或私人存储的 GUID,但支付欺诈预防和电话除外。
它对于设备上的应用程序安装来说是独一无二的,所以当用户卸载应用程序时 - 它会被清除,所以它不是 100% 可靠的,但它是次优的。
注意 从今天起,FirebaseInstanceId
已被弃用,您应该改用 FirebaseInstallations
。
要使用 FirebaseInstallations
,请将 latest firebase-messaging dependency 添加到您的 gradle
implementation 'com.google.firebase:firebase-messaging:23.0.0'
并使用以下代码获取 Firebase ID:
FirebaseInstallations.getInstance().getId().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
String firebaseIdentifier = task.getResult();
// Do what you need with firebaseIdentifier
}
});
如果您需要将设备标识存储在远程服务器上,则不要按原样(纯文本)存储它,而是 hash with salt。
今天,这不仅是一种最佳做法,而且您实际上必须根据 GDPR - identifiers 和类似法规依法执行。
您也可以考虑 Wi-Fi 适配器的 MAC 地址。像这样检索:
WifiManager wm = (WifiManager)Ctxt.getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getMacAddress();
需要清单中的权限 android.permission.ACCESS_WIFI_STATE
。
据报道,即使在未连接 Wi-Fi 时也可用。如果上面答案中的乔在他的许多设备上试一试,那就太好了。
在某些设备上,关闭 Wi-Fi 时它不可用。
注意: 从 Android 6.x 开始,它返回一致的假 mac 地址:02:00:00:00:00:00
android.permission.ACCESS_WIFI_STATE
02:00:00:00:00:00
有相当有用的信息 here。
它涵盖了五种不同的 ID 类型:
IMEI(仅适用于使用手机的 Android 设备;需要 android.permission.READ_PHONE_STATE) Pseudo-Unique ID(适用于所有 Android 设备) Android ID(可以为空,可以在恢复出厂设置时更改,可以在 root 手机上更改) WLAN MAC 地址字符串(需要 android.permission.ACCESS_WIFI_STATE) BT MAC 地址字符串(带蓝牙的设备,需要 android.permission.BLUETOOTH)
官方 Android 开发者博客现在有一篇关于这个主题的完整文章,Identifying App Installations。
在 Google I/O,Reto Meier 发布了关于如何解决此问题的可靠答案,该答案应满足大多数开发人员在跨安装跟踪用户的需求。安东尼诺兰在他的回答中表明了方向,但我想我会写出完整的方法,以便其他人可以轻松地看到如何去做(我花了一段时间才弄清楚细节)。
这种方法将为您提供一个匿名的、安全的用户 ID,该用户 ID 将在不同设备(基于主要 Google 帐户)和安装中对用户保持不变。基本方法是生成随机用户 ID 并将其存储在应用程序的共享首选项中。然后,您使用 Google 的备份代理将链接到云中的 Google 帐户的共享首选项存储起来。
让我们来看看完整的方法。首先,我们需要使用 Android 备份服务为我们的 SharedPreferences 创建一个备份。首先通过 http://developer.android.com/google/backup/signup.html
注册您的应用程序。
Google 将为您提供一个备份服务密钥,您需要将其添加到清单中。您还需要告诉应用程序使用 BackupAgent,如下所示:
<application android:label="MyApplication"
android:backupAgent="MyBackupAgent">
...
<meta-data android:name="com.google.android.backup.api_key"
android:value="your_backup_service_key" />
</application>
然后您需要创建备份代理并告诉它使用辅助代理来共享首选项:
public class MyBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "user_preferences";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
要完成备份,您需要在主 Activity 中创建 BackupManager 的实例:
BackupManager backupManager = new BackupManager(context);
最后创建一个用户 ID,如果它不存在,并将其存储在 SharedPreferences 中:
public static String getUserID(Context context) {
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(
MyBackupAgent.PREFS, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
//backup the changes
BackupManager mBackupManager = new BackupManager(context);
mBackupManager.dataChanged();
}
}
return uniqueID;
}
即使用户移动设备,此 User_ID 现在将在安装中保持不变。
有关此方法的更多信息,请参阅 Reto's talk。
有关如何实施备份代理的完整详细信息,请参阅Data Backup。我特别推荐底部的测试部分,因为备份不会立即发生,因此要进行测试,您必须强制备份。
我认为这肯定是为唯一 ID 构建骨架的有效方式......检查一下。
伪唯一 ID,适用于所有 Android 设备 某些设备没有手机(例如平板电脑),或者出于某种原因,您不想包含 READ_PHONE_STATE 权限。您仍然可以阅读 ROM 版本、制造商名称、CPU 类型和其他硬件详细信息等详细信息,如果您想将 ID 用于序列密钥检查或其他一般用途,这将非常适合。以这种方式计算的 ID 不会是唯一的:可以找到具有相同 ID 的两个设备(基于相同的硬件和 ROM 映像),但实际应用程序中的变化可以忽略不计。为此,您可以使用 Build 类:
String m_szDevIDShort = "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
大多数 Build 成员都是字符串,我们在这里所做的是获取它们的长度并通过模数转换它。我们有 13 个这样的数字,我们在前面添加两个(35)以具有与 IMEI 相同大小的 ID(15 位)。这里还有其他的可能性很好,看看这些字符串。返回类似 355715565309247
的内容。不需要特别许可,使这种方法非常方便。
(额外信息:上面给出的技术是从 Pocket Magic 上的一篇文章中复制的。)
以下代码使用隐藏的 Android API 返回设备序列号。但是,此代码不适用于三星 Galaxy Tab,因为此设备上未设置“ro.serialno”。
String serial = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ro.serialno");
}
catch (Exception ignored) {
}
使用下面的代码,您可以将 Android 操作系统设备的唯一设备 ID 作为字符串获取。
deviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
在 API 级别 9(Android 2.3 - Gingerbread)的 Build
类中添加了一个 Serial 字段。文档说它代表硬件序列号。因此,如果它存在于设备上,它应该是唯一的。
我不知道 API 级别 >= 9 的所有设备是否都支持它(=not null)。
我要补充一件事——我有一种独特的情况。
使用:
deviceId = Secure.getString(this.getContext().getContentResolver(), Secure.ANDROID_ID);
事实证明,即使我的 Viewsonic G Tablet 报告的 DeviceID 不是 Null,每个 G Tablet 都报告相同的数字。
让玩“口袋帝国”变得有趣,它使您可以根据“唯一”设备 ID 即时访问某人的帐户。
我的设备没有手机收音机。
有关如何为安装您的应用程序的每台 Android 设备获取唯一标识符的详细说明,请参阅官方 Android 开发者博客帖子Identifying App Installations。
似乎最好的方法是让您在安装时自己生成一个,然后在重新启动应用程序时阅读它。
我个人认为这是可以接受的,但并不理想。 Android 提供的任何标识符都不适用于所有情况,因为大多数标识符取决于手机的无线电状态(Wi-Fi 开/关、蜂窝网络开/关、蓝牙开/关)。其他的,如 Settings.Secure.ANDROID_ID
必须由制造商实现,并且不能保证是唯一的。
以下是将数据写入安装文件的示例,该安装文件将与应用程序在本地保存的任何其他数据一起存储。
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
在类文件中添加以下代码:
final TelephonyManager tm = (TelephonyManager) getBaseContext()
.getSystemService(SplashActivity.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
Log.v("DeviceIMEI", "" + tmDevice);
tmSerial = "" + tm.getSimSerialNumber();
Log.v("GSM devices Serial Number[simcard] ", "" + tmSerial);
androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
Log.v("androidId CDMA devices", "" + androidId);
UUID deviceUuid = new UUID(androidId.hashCode(),
((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
String deviceId = deviceUuid.toString();
Log.v("deviceIdUUID universally unique identifier", "" + deviceId);
String deviceModelName = android.os.Build.MODEL;
Log.v("Model Name", "" + deviceModelName);
String deviceUSER = android.os.Build.USER;
Log.v("Name USER", "" + deviceUSER);
String devicePRODUCT = android.os.Build.PRODUCT;
Log.v("PRODUCT", "" + devicePRODUCT);
String deviceHARDWARE = android.os.Build.HARDWARE;
Log.v("HARDWARE", "" + deviceHARDWARE);
String deviceBRAND = android.os.Build.BRAND;
Log.v("BRAND", "" + deviceBRAND);
String myVersion = android.os.Build.VERSION.RELEASE;
Log.v("VERSION.RELEASE", "" + myVersion);
int sdkVersion = android.os.Build.VERSION.SDK_INT;
Log.v("VERSION.SDK_INT", "" + sdkVersion);
在 AndroidManifest.xml 中添加:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
有很多不同的方法可以解决这些 ANDROID_ID
问题(有时可能是 null
或特定型号的设备总是返回相同的 ID),各有利弊:
实现自定义 ID 生成算法(基于应该是静态且不会更改的设备属性 -> 谁知道)
滥用其他 ID,如 IMEI、序列号、Wi-Fi/蓝牙-MAC 地址(它们不会在所有设备上都存在或需要额外的权限)
我自己更喜欢为 Android 使用现有的 OpenUDID 实现(参见 https://github.com/ylechelle/OpenUDID)(参见 https://github.com/vieux/OpenUDID)。对于上述问题,它很容易集成并使用带有后备的 ANDROID_ID
。
这里有 30 多个答案,有些是相同的,有些是独一无二的。该答案基于其中几个答案。其中之一是@Lenn Dolling 的回答。
它结合了 3 个 ID 并创建了一个 32 位的十六进制字符串。它对我来说效果很好。
3 个 ID 分别是:
Pseudo-ID - 根据物理设备规格生成
ANDROID_ID - Settings.Secure.ANDROID_ID
蓝牙地址< /strong> - 蓝牙适配器地址
它将返回如下内容: 551F27C060712A72730B0A0F734064B1
注意:您始终可以向 longId
字符串添加更多 ID。例如,序列号。 wifi 适配器地址。 IMEI。这样,您就可以使其在每个设备上都更加独特。
@SuppressWarnings("deprecation")
@SuppressLint("HardwareIds")
public static String generateDeviceIdentifier(Context context) {
String pseudoId = "35" +
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;
String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String btId = "";
if (bluetoothAdapter != null) {
btId = bluetoothAdapter.getAddress();
}
String longId = pseudoId + androidId + btId;
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(longId.getBytes(), 0, longId.length());
// get md5 bytes
byte md5Bytes[] = messageDigest.digest();
// creating a hex string
String identifier = "";
for (byte md5Byte : md5Bytes) {
int b = (0xFF & md5Byte);
// if it is a single digit, make sure it have 0 in front (proper padding)
if (b <= 0xF) {
identifier += "0";
}
// add number to string
identifier += Integer.toHexString(b);
}
// hex string to uppercase
identifier = identifier.toUpperCase();
return identifier;
} catch (Exception e) {
Log.e("TAG", e.toString());
}
return "";
}
longId
。像这样更改这一行: String longId = pseudoId + androidId + btId + UUID.randomUUID().toString();
这保证生成的 ID 将是唯一的。
IMEI 怎么样。这对于 Android 或其他移动设备来说是独一无二的。
我的两分钱 - 注意这是一个设备(错误)唯一 ID - 不是 Android developers's blog 中讨论的安装。
请注意,@emmby 提供的 solution 回退到每个应用程序 ID,因为 SharedPreferences 不会跨进程同步(请参阅 here 和 here)。所以我完全避免了这一点。
相反,我封装了在枚举中获取(设备)ID 的各种策略——更改枚举常量的顺序会影响获取 ID 的各种方式的优先级。返回第一个非空 ID 或抛出异常(根据 Java 不赋予 null 含义的良好做法)。因此,例如,我首先拥有 TELEPHONY - 但一个不错的默认选择是 ANDROID_ID 测试版:
import android.Manifest.permission;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
// TODO : hash
public final class DeviceIdentifier {
private DeviceIdentifier() {}
/** @see http://code.google.com/p/android/issues/detail?id=10603 */
private static final String ANDROID_ID_BUG_MSG = "The device suffers from "
+ "the Android ID bug - its ID is the emulator ID : "
+ IDs.BUGGY_ANDROID_ID;
private static volatile String uuid; // volatile needed - see EJ item 71
// need lazy initialization to get a context
/**
* Returns a unique identifier for this device. The first (in the order the
* enums constants as defined in the IDs enum) non null identifier is
* returned or a DeviceIDException is thrown. A DeviceIDException is also
* thrown if ignoreBuggyAndroidID is false and the device has the Android ID
* bug
*
* @param ctx
* an Android constant (to retrieve system services)
* @param ignoreBuggyAndroidID
* if false, on a device with the android ID bug, the buggy
* android ID is not returned instead a DeviceIDException is
* thrown
* @return a *device* ID - null is never returned, instead a
* DeviceIDException is thrown
* @throws DeviceIDException
* if none of the enum methods manages to return a device ID
*/
public static String getDeviceIdentifier(Context ctx,
boolean ignoreBuggyAndroidID) throws DeviceIDException {
String result = uuid;
if (result == null) {
synchronized (DeviceIdentifier.class) {
result = uuid;
if (result == null) {
for (IDs id : IDs.values()) {
try {
result = uuid = id.getId(ctx);
} catch (DeviceIDNotUniqueException e) {
if (!ignoreBuggyAndroidID)
throw new DeviceIDException(e);
}
if (result != null) return result;
}
throw new DeviceIDException();
}
}
}
return result;
}
private static enum IDs {
TELEPHONY_ID {
@Override
String getId(Context ctx) {
// TODO : add a SIM based mechanism ? tm.getSimSerialNumber();
final TelephonyManager tm = (TelephonyManager) ctx
.getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null) {
w("Telephony Manager not available");
return null;
}
assertPermission(ctx, permission.READ_PHONE_STATE);
return tm.getDeviceId();
}
},
ANDROID_ID {
@Override
String getId(Context ctx) throws DeviceIDException {
// no permission needed !
final String andoidId = Secure.getString(
ctx.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
if (BUGGY_ANDROID_ID.equals(andoidId)) {
e(ANDROID_ID_BUG_MSG);
throw new DeviceIDNotUniqueException();
}
return andoidId;
}
},
WIFI_MAC {
@Override
String getId(Context ctx) {
WifiManager wm = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
if (wm == null) {
w("Wifi Manager not available");
return null;
}
assertPermission(ctx, permission.ACCESS_WIFI_STATE); // I guess
// getMacAddress() has no java doc !!!
return wm.getConnectionInfo().getMacAddress();
}
},
BLUETOOTH_MAC {
@Override
String getId(Context ctx) {
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
if (ba == null) {
w("Bluetooth Adapter not available");
return null;
}
assertPermission(ctx, permission.BLUETOOTH);
return ba.getAddress();
}
}
// TODO PSEUDO_ID
// http://www.pocketmagic.net/2011/02/android-unique-device-id/
;
static final String BUGGY_ANDROID_ID = "9774d56d682e549c";
private final static String TAG = IDs.class.getSimpleName();
abstract String getId(Context ctx) throws DeviceIDException;
private static void w(String msg) {
Log.w(TAG, msg);
}
private static void e(String msg) {
Log.e(TAG, msg);
}
}
private static void assertPermission(Context ctx, String perm) {
final int checkPermission = ctx.getPackageManager().checkPermission(
perm, ctx.getPackageName());
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Permission " + perm + " is required");
}
}
// =========================================================================
// Exceptions
// =========================================================================
public static class DeviceIDException extends Exception {
private static final long serialVersionUID = -8083699995384519417L;
private static final String NO_ANDROID_ID = "Could not retrieve a "
+ "device ID";
public DeviceIDException(Throwable throwable) {
super(NO_ANDROID_ID, throwable);
}
public DeviceIDException(String detailMessage) {
super(detailMessage);
}
public DeviceIDException() {
super(NO_ANDROID_ID);
}
}
public static final class DeviceIDNotUniqueException extends
DeviceIDException {
private static final long serialVersionUID = -8940090896069484955L;
public DeviceIDNotUniqueException() {
super(ANDROID_ID_BUG_MSG);
}
}
}
使用 TelephonyManager 和 ANDROID_ID 的 Android 操作系统设备的唯一设备 ID 作为字符串,通过以下方式获得:
String deviceId;
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId();
}
else {
deviceId = Secure.getString(
getApplicationContext().getContentResolver(),
Secure.ANDROID_ID);
}
但我强烈推荐 Google 建议的方法,请参阅 Identifying App Installations。
这是我生成唯一ID的方式:
public static String getDeviceId(Context ctx)
{
TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
String tmDevice = tm.getDeviceId();
String androidId = Secure.getString(ctx.getContentResolver(), Secure.ANDROID_ID);
String serial = null;
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) serial = Build.SERIAL;
if(tmDevice != null) return "01" + tmDevice;
if(androidId != null) return "02" + androidId;
if(serial != null) return "03" + serial;
// other alternatives (i.e. Wi-Fi MAC, Bluetooth MAC, etc.)
return null;
}
另一种方法是在没有任何权限的应用程序中使用 /sys/class/android_usb/android0/iSerial
。
user@creep:~$ adb shell ls -l /sys/class/android_usb/android0/iSerial
-rw-r--r-- root root 4096 2013-01-10 21:08 iSerial
user@creep:~$ adb shell cat /sys/class/android_usb/android0/iSerial
0A3CXXXXXXXXXX5
要在 Java 中执行此操作,只需使用 FileInputStream 打开 iSerial 文件并读出字符。请确保将其包装在异常处理程序中,因为并非所有设备都有此文件。
至少已知以下设备具有此文件的世界可读性:
银河连结
连结小号
摩托罗拉 Xoom 3G
东芝AT300
宏达一V
迷你MK802
三星盖乐世 S II
您还可以查看我的博文Leaking Android hardware serial number to unprivileged apps,我在其中讨论了哪些其他文件可供参考。
对于特定 Android 设备的硬件识别,您可以检查 MAC 地址。
你可以这样做:
在 AndroidManifest.xml 中
<uses-permission android:name="android.permission.INTERNET" />
现在在您的代码中:
List<NetworkInterface> interfacesList = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface interface : interfacesList) {
// This will give you the interface MAC ADDRESS
interface.getHardwareAddress();
}
在每个 Android 设备中,它们至少有一个“wlan0”接口,即 WI-FI 芯片。即使未打开 WI-FI,此代码也有效。
PS 它们是您将从包含 MACS 的列表中获得的一堆其他接口,但这可以在手机之间改变。
当设备没有电话功能时,我使用以下代码获取 IMEI
或使用 Secure.ANDROID_ID
作为替代:
String identifier = null;
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE));
if (tm != null)
identifier = tm.getDeviceId();
if (identifier == null || identifier .length() == 0)
identifier = Secure.getString(activity.getContentResolver(),Secure.ANDROID_ID);
TelephonyManger.getDeviceId() 返回唯一的设备 ID,例如,GSM 的 IMEI 和 CDMA 电话的 MEID 或 ESN。
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String myAndroidDeviceId = mTelephony.getDeviceId();
但我建议使用:
Settings.Secure.ANDROID_ID 将 Android ID 作为唯一的 64 位十六进制字符串返回。
String myAndroidDeviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
有时 TelephonyManger.getDeviceId() 将返回 null,因此为了确保唯一的 id,您将使用此方法:
public String getUniqueID(){
String myAndroidDeviceId = "";
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null){
myAndroidDeviceId = mTelephony.getDeviceId();
}else{
myAndroidDeviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
}
return myAndroidDeviceId;
}
谷歌实例 ID
在 2015 年 I/O 大会上发布;在 Android 上需要播放服务 7.5。
https://developers.google.com/instance-id/
https://developers.google.com/instance-id/guides/android-implementation
InstanceID iid = InstanceID.getInstance( context ); // Google docs are wrong - this requires context
String id = iid.getId(); // blocking call
Google 似乎打算将此 ID 用于识别 Android、Chrome 和 iOS 上的安装。
它识别的是安装而不是设备,但话说回来,ANDROID_ID(这是公认的答案)现在也不再识别设备。使用 ARC 运行时,每次安装 (details here) 都会生成一个新的 ANDROID_ID,就像这个新的实例 ID 一样。此外,我认为识别安装(而不是设备)是我们大多数人真正想要的。
实例 ID 的优势
在我看来,Google 打算将其用于此目的(识别您的安装),它是跨平台的,并且可以用于许多其他目的(参见上面的链接)。
如果您使用 GCM,那么您最终将需要使用此实例 ID,因为您需要它来获取 GCM 令牌(它取代了旧的 GCM 注册 ID)。
缺点/问题
在当前实现 (GPS 7.5) 中,实例 ID 在您的应用程序请求时从服务器检索。这意味着上面的调用是一个阻塞调用——在我的非科学测试中,如果设备在线,则需要 1-3 秒,如果离线,则需要 0.5-1.0 秒(大概这是它在放弃和生成之前等待的时间)随机 ID)。这是在北美使用 Android 5.1.1 和 GPS 7.5 在 Nexus 5 上进行的测试。
如果您将 ID 用于他们想要的目的 - 例如。应用程序身份验证、应用程序识别、GCM - 我认为这 1-3 秒可能会很麻烦(当然取决于您的应用程序)。
Google 现在有一个 Advertising ID。
这也可以使用,但请注意:
广告 ID 是用户特定的、唯一的、可重置的 ID
和
使用户能够在 Google Play 应用程序中重置其标识符或选择退出基于兴趣的广告。
因此,虽然这个 id 可能会改变,但似乎很快 we may not have a choice,取决于这个 id 的用途。
高温高压
了解 Android 设备中可用的唯一 ID。使用这个官方指南。
唯一标识符的最佳实践:
IMEI、Mac 地址、实例 ID、GUID、SSAID、广告 ID、安全网 API 以验证设备。
https://developer.android.com/training/articles/user-data-ids