一前痘、使用IMEI
但是僅僅對Android手機有效,并且添加權(quán)限:android.permission.READ_PHONE_STATE
public synchronized static String getid(Context context) {
TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String ID= TelephonyMgr.getDeviceId();
return ID;
}
二担忧、WLAN MAC Address 使用網(wǎng)卡地址
基本上的Android設備都配備WLAN芹缔,可以通過WLAN地址來作為設備碼,同理瓶盛,也需要加入android.permission.ACCESS_WIFI_STATE 權(quán)限最欠,否則返回null.
public synchronized static String getMacid(Context context) {
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
String WLANMAC = wm.getConnectionInfo().getMacAddress();
return WLANMAC ;
}
三示罗、使用藍牙地址作為標識
在有藍牙的設備上運行。并且要加入android.permission.BLUETOOTH 權(quán)限.
public synchronized static String getMacid(Context context) {
BluetoothAdapter mBlueth= BluetoothAdapter.getDefaultAdapter();
String mBluethId= mBlueth.getAddress();
return mBluethId;
}
四芝硬、Installtion ID
考慮到Android設備的多樣性蚜点,比如一些平板沒有通話功能,或者部分低價設備沒有WLAN或者藍牙拌阴,甚至用戶不愿意賦予APP這些需要的權(quán)限绍绘,我們就使用無需權(quán)限的方法;這種方式的原理是在程序安裝后第一次運行時生成一個ID,該方式和設備唯一標識不一樣迟赃,不同的應用程序會產(chǎn)生不同的ID陪拘,同一個程序重新安裝也會不同。所以這不是設備的唯一ID纤壁,但是可以保證每個用戶的ID是不同的左刽。可以說是用來標識每一份應用程序的唯一ID(即Installtion ID)摄乒,可以用來跟蹤應用的安裝數(shù)量等悠反。
public class GetDeviceid {
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();
}
}
五、Combined Device ID
綜上所述馍佑,我們一共有五種方式取得設備的唯一標識吸申。它們中的一些可能會返回null礁叔,或者由于硬件缺失屋剑、權(quán)限問題等獲取失敗震叮。但你總能獲得至少一個能用。所以舅世,最好的方法就是通過拼接旦委,或者拼接后的計算出的MD5值來產(chǎn)生一個結(jié)果。
String m_szLongID = m_szImei + m_szDevIDShort + m_szAndroidID+ m_szWLANMAC + m_szBTMAC;
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
m.update(m_szLongID.getBytes(),0,m_szLongID.length());
// get md5 bytes
byte p_md5Data[] = m.digest();
// create a hex string
String m_szUniqueID = new String();
for (int i=0;i<p_md5Data.length;i++) {
int b = (0xFF & p_md5Data[i]);
if (b <= 0xF) {
m_szUniqueID+="0";
}
// add number to string
m_szUniqueID+=Integer.toHexString(b);
}
// hex string to uppercase
m_szUniqueID = m_szUniqueID.toUpperCase();