Android设备的唯一标识
IMEI
权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
获取IMEI
/**
* 获取IMEI
*
* @return IMEI
*/
private String getIMEI() {
try {
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
return TelephonyMgr.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
WLAN MAC Address
权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
获取MAC地址
/**
* 获取WLAN MAC Address
*
* @return MAC地址
*/
private String getWLANMacAddress() {
try {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getMacAddress();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
BT MAC Address
权限
<uses-permission android:name="android.permission.BLUETOOTH" />
获取MAC地址
/**
* 获取BT MAC Address
*
* @return MAC地址
*/
private String getBTMacAddress() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return bluetoothAdapter.getAddress();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
MD5加密
附加一个MD5的加密算法,考虑在某些特殊设备上可能获取不到某个ID,可以获取多个ID,组合起来,通过MD5算法,得到一个32位的唯一标识
/**
* MD5加密
*
* @param text 要加密的字符串
* @return 加密后的32位结果
*/
private String digest(String text) {
try {
// 创建一个MD5加密算法
MessageDigest digest = MessageDigest.getInstance("MD5");
// 创建StringBuffer保存十六进制数据
StringBuffer sb = new StringBuffer();
// 换成字节数组
byte[] bytes = digest.digest(text.getBytes());
// 遍历字节数组加密
for (byte bt : bytes) {
// 将负数转换为正数
int i = bt & 0xff;
// 将十进制转换为十六进制
String hex = Integer.toHexString(i);
// 如果不够2位,前面补0
if (2 > hex.length()) {
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
例:
String text = getWLANMacAddress() + getBTMacAddress() + getIMEI();
String md5 = digest(text);
Toast.makeText(this, "MD5:" + md5, Toast.LENGTH_SHORT).show();