語言: CN / TW / HK


本文已參與 「掘力星計劃」 ,贏取創作大禮包,挑戰創作激勵金。



以前我都是直接獲取IMEI來作為設備的唯一標識 var imei: String = "" val tm: TelephonyManager = context.getSystemService(Service.TELEPHONY_SERVICE) as TelephonyManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { imei = tm.imei } else { imei = tm.deviceId } Log.e("TAG","$imei") imei和deviceId都有一個重載函數,主要是區別雙卡的一個情況


Android6.0以後我們加一個動態權限即可,但是用户只要拒絕就沒辦法獲取了,不過一般來説我們會有個彈框來引導用户同意 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> Android 10.0 谷歌再一次收緊權限


<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" /> 如果你把他放到AndroidManifest會報錯


官方也説了,你要是弟弟(9.0 以下)我給你報null,你要是10.0 還敢用我就直接拋異常. 後面在stackoverflow上面找到了一個辦法

``` public class DeviceUuidFactory { protected static final String PREFS_FILE = "device_id.xml"; protected static final String PREFS_DEVICE_ID = "device_id"; protected 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 () {
                            uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                        } else {
                            @SuppressLint("MissingPermission") 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.

 * @return a UUID that may be used to uniquely identify your device for most purposes.
public String getDeviceUuid() {
    return uuid.toString();

} ```

這個類的意思是,首先他會去SharedPreferences查詢有沒有,沒有的話再去查詢ANDROID_ID,後面判斷了是否是9774d56d682e549c,因為有的廠商手機好多ANDROID_ID都是這個,所以判斷一下,防止好幾萬個人用一個賬號,不然那就笑嘻嘻了,後面如果真等於9774d56d682e549c了,就通過下面的 @SuppressLint("MissingPermission") final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();



``` //阿里雲唯一設備id val deviceId = PushServiceFactory.getCloudPushService().deviceId

//Mob CloudPushService pushService = PushServiceFactory.getCloudPushService(); pushService.register(applicationContext, new CommonCallback() { @Override public void onSuccess(String response) { Log.e("TAG", "onSuccess: "+response); }

public void onFailed(String errorCode, String errorMessage) {


//友盟唯一設備ID val pushAgent = PushAgent.getInstance(context) pushAgent.register(object : UPushRegisterCallback { override fun onSuccess(deviceToken: String) { //註冊成功會返回deviceToken deviceToken是推送消息的唯一標誌 Log.i(TAG, "註冊成功:deviceToken:--> $deviceToken") }

override fun onFailure(errCode: String, errDesc: String) {
    Log.e(TAG, "註冊失敗:--> code:$errCode, desc:$errDesc")

}) ```