ANDROID_ID

在设备首次启动时,系统会随机生成一个64位的数字,并把这个数字以16进制字符串的形式保存下来,这个16进制的字符串就是ANDROID_ID,当设备被wipe后该值会被重置。可以通过下面的方法获取:

import android.provider.Settings;
String ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
1
2
ANDROID_ID可以作为设备标识,但需要注意:
厂商定制系统的Bug:不同的设备可能会产生相同的ANDROID_ID:9774d56d682e549c。
厂商定制系统的Bug:有些设备返回的值为null。
设备差异:对于CDMA设备,ANDROID_ID和TelephonyManager.getDeviceId() 返回相同的值。

Sim Serial Number
装有SIM卡的设备,可以通过下面的方法获取到Sim Serial Number:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String SimSerialNumber = tm.getSimSerialNumber();
注意:对于CDMA设备,返回的是一个空值!

import java.util.UUID;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.provider.Settings;
@SuppressLint("NewApi") public class AndroidUUID
{
static public String getDeviceId(Context context) {
StringBuilder deviceId = new StringBuilder();

// 渠道标志
deviceId.append("a");
try {
//MAC
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String wifiMac = info.getMacAddress();

if(wifiMac != null && !wifiMac.isEmpty()){
deviceId.append("mac");
deviceId.append(wifiMac);
return deviceId.toString();
}

//IMEI
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
if(imei != null && !imei.isEmpty()){
deviceId.append("imei");
deviceId.append(imei);
return deviceId.toString();
}

String androidID = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
if(androidID != null && !androidID.isEmpty()){
deviceId.append("androidid");
deviceId.append(androidID);
return deviceId.toString();
}

//序列号(sn)
String sn = tm.getSimSerialNumber();
if(sn != null && !sn.isEmpty()){
deviceId.append("sn");
deviceId.append(sn);
return deviceId.toString();
}

//如果上面都没有, 则生成一个id:随机码
String uuid = getUUID(context);
if(uuid != null && !uuid.isEmpty()){
deviceId.append("uuid");
deviceId.append(uuid);
return deviceId.toString();
}

} catch (Exception e) {
e.printStackTrace();
deviceId.append("uuid").append(getUUID(context));
}
return deviceId.toString();
}

/**
* 得到全局唯一UUID
*/

public static String getUUID(Context context){
String uuid = null;

SharedPreferences sp = context.getSharedPreferences("SP", Context.MODE_PRIVATE);

if(sp != null){
uuid = sp.getString("uuid", "");
}

if(uuid == null || uuid.isEmpty()){
uuid = UUID.randomUUID().toString();
SharedPreferences.Editor eidtor = sp.edit();
eidtor.putString("uuid", uuid);
eidtor.commit();
}
return uuid;
}
}

猜你喜欢

转载自www.cnblogs.com/ly570/p/11667869.html