Android设备有唯一的ID吗?如果有,使用Java访问它的简单方法是什么?
当前回答
此外,您还可以考虑Wi-Fi适配器的MAC地址。检索方式如下:
WifiManager wm = (WifiManager)Ctxt.getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getMacAddress();
清单中需要权限android.permission.ACCESS_WIFI_STATE。
据报道,即使未连接Wi-Fi,也可用。如果上面的答案中的乔在他的许多设备上尝试一下,那就太好了。
在某些设备上,当Wi-Fi关闭时,它不可用。
注意:从Android6.x,它返回一致的假mac地址:02:00:00:00:00
其他回答
有很多不同的方法可以解决ANDROID_ID问题(有时可能为空,或者特定型号的设备总是返回相同的ID),有利弊:
实现自定义ID生成算法(基于应该是静态且不会更改的设备财产->谁知道呢)滥用其他ID,如IMEI、序列号、Wi-Fi/蓝牙MAC地址(它们不会存在于所有设备上,或者需要额外的权限)
我自己更喜欢使用现有的OpenUDID实现(请参见https://github.com/ylechelle/OpenUDID)适用于Android(请参见https://github.com/vieux/OpenUDID). 它很容易集成并利用ANDROID_ID和上述问题的回退。
Settings.Secure#ANDROID_ID返回每个用户64位十六进制字符串的唯一ANDROID ID。
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
IMEI怎么样。这对于Android或其他移动设备来说是独一无二的。
以下是我如何生成唯一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;
}
当设备没有电话功能时,我使用以下代码获取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);
推荐文章
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS
- Android M权限:对shouldShowRequestPermissionRationale()函数的使用感到困惑
- 为什么构建类型与产品风味不同?
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别