关于android设备唯一区分device id的取得

有些apk为了区分唯一设备,需要用到一个device id。
1. 取得设备的MAC address
   如果用户没有通过wifi连网路的话,就无法取得。
2. 使用TelephonyManager的getDeviceId()
3. 另外还有一个android系统的唯一区分ANDROID_ID,
   Settings.Secure#ANDROID_ID returns the Android ID as an unique 64-bit hex string.

   import android.provider.Settings.Secure;
   private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID); 

更多解决方案参考网页:http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id
                  http://android-developers.blogspot.tw/2011/03/identifying-app-installations.html
//===========================================
// question
//===========================================
Do Android devices have a unique id, and if so, what is a simple way to access it via java?
//===========================================
// answer 1
//===========================================
There are many answers to this question, most of which will only work "some" of the time, and unfortunately that's not good enough.

Based on my tests of devices (all phones, at least one of which is not activated):

    * All devices tested returned a value for TelephonyManager.getDeviceId()
    * All GSM devices (all tested with a SIM) returned a value for TelephonyManager.getSimSerialNumber()
    * All CDMA devices returned null for getSimSerialNumber() (as expected)
    * All devices with a Google account added returned a value for ANDROID_ID
    * All CDMA devices returned the same value (or derivation of the same value) for both ANDROID_ID and TelephonyManager.getDeviceId() -- as long as a Google account has been added during setup.
    * I did not yet have a chance to test GSM devices with no SIM, a GSM device with no Google account added, or any of the devices in airplane mode.

So if you want something unique to the device itself, TM.getDeviceId() should be sufficient. Obviously some users are more paranoid than others, so it might be useful to hash 1 or more of these identifiers, so that the string is still virtually unique to the device, but does not explicitly identify the user's actual device. For example, using String.hashCode(), combined with a UUID:

复制代码
    final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

    final String tmDevice, tmSerial, androidId;
    tmDevice = "" + tm.getDeviceId();
    tmSerial = "" + tm.getSimSerialNumber();
    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
    String deviceId = deviceUuid.toString();
复制代码

might result in something like: 00000000-54b3-e7c7-0000-000046bffd97

It works well enough for me.

As Richard mentions below, don't forget that you need permission to read the TelephonyManager properties, so add this to your manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
-----------------------------------------------------------------------------------
elephony-based ID won't be there on tablet devices, neh? – Seva Alekseyev Jun 23 '10 at 14:27

Hence why I said most won't work all the time :) I've yet to see any answer to this question that is reliable for all devices, all device types, and all hardware configurations. That's why this question is here to begin with. It's pretty clear that there is no end-all-be-all solution to this. Individual device manufacturers may have device serial numbers, but those are not exposed for us to use, and it is not a requirement. Thus we're left with what is available to us. – Joe Jun 29 '10 at 19:40

Will you update your answer after more testing? It would be quite interesting. – liori Jan 31 '11 at 20:12

The code sample works great. Remember to add <uses-permission android:name="android.permission.READ_PHONE_STATE" /> to the manifest file. If storing in a database, the returned string is 36 characters long. – Richard Feb 27 '11 at 22:28

@softarn: I believe what you're referring to is the Android Developer Blog that emmby already linked to, which explains what you are trying to say, so perhaps you should have simply upvoted his comment instead. Either way, as emmby mentions in his answer, there are still problems even with the blog info. The question asks for a unique DEVICE identifier (not installation identifier), so I disagree with your statement. The blog is making an assumption that what you want is not necessarily to track the device, whereas the question asks for just that. I agree with the blog otherwise. – Joe Jul 22 '11 at 0:45
//===========================================
// answer 2
//===========================================
As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.

However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:

    * ANDROID_ID is the preferred device identifier. ANDROID_ID is perfectly reliable on versions of Android <=2.1 or >=2.3. Only 2.2 has the problems mentioned in the post.
    * Several devices by several manufacturers are affected by the ANDROID_ID bug in 2.2.
    * As far as I've been able to determine, all affected devices have the same ANDROID_ID, which is 9774d56d682e549c. Which is also the same device id reported by the emulator, btw.
    * Google believes that OEMs have patched the issue for many or most of their devices, but I was able to verify that as of the beginning of April 2011, at least, it's still quite easy to find devices that have the broken ANDROID_ID.

Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).

Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.

Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.

复制代码
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class DeviceUuidFactory {
    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";

    protected volatile 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 (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                            } else {
                                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.
     *
     * @see http://code.google.com/p/android/issues/detail?id=10603
     *
     * @return a UUID that may be used to uniquely identify your device for most purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }
}
复制代码

-----------------------------------------------------------------------
Shouldn't you be hashing the various IDs so that they're all the same size? Additionally, you should be hashing the device ID in order to not accidentally expose private information. – Steve Pomeroy Apr 11 '11 at 20:10
    
Also, a device whose configuration causes the Device ID to be used will tie the ID to the device, not necessarily the user. That ID will survive factory resetting, which could be potentially bad. Maybe the Device ID could be hashed with something that reports the time of the last factory reset? – Steve Pomeroy Apr 11 '11 at 20:12

Good points, Steve. I updated the code to always return a UUID. This ensure that a) the generated IDs are always the same size, and b) the android and device IDs are hashed before being returned to avoid accidentally exposing personal information. I also updated the description to note that device ID will persist across factory resets and that this may not be desirable for some users. – emmby Apr 11 '11 at 21:53
    
I believe you are incorrect; the preferred solution is to track installations, not device identifiers. Your code is substantially longer and more complex than that in the blog post and it's not obvious to me that it adds any value. – Tim Bray Apr 12 '11 at 4:58 
    
ANDROID_ID can change on factory reset, so it cannot identify devices as well – Sam Quest May 19 '11 at 8:12

//===========================================
// answer 3
//===========================================
Also you might consider the WiFi adapter's MAC address. Retrieved thusly:

WifiManager wm = (WifiManager)Ctxt.getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getMacAddress();

Requires permission android.permission.ACCESS_WIFI_STATE in the manifest.

Reported to be available even when WiFi is not connected. If Joe from the answer above gives this one a try on his many devices, that'd be nice.

EDIT: on some devices, it's not available when WiFi is turned off.
----------------------------------------------------------------------------
This required android.permission.ACCESS_WIFI_STATE – ohhorob Nov 1 '10 at 4:41
    
what about wifi-less devices? – Axarydax Dec 22 '10 at 10:28
2      
    
They exist? I'd rather envision a telephony-less device (AKA tablet)... – Seva Alekseyev Dec 22 '10 at 14:23
    
I know this question is old - but this is a great idea. I used the BT mac ID in my app, but only because it requires BT to function. Show me an Android device that's worth developing for that does NOT have WiFi. – Jack Aug 29 '11 at 21:27
    
I think you'll find that it's unavailable when WiFi is off, on pretty much all android devices. Turning WiFi off removes the device at kernel level. – chrisdowney May 21 at 23:38
//===========================================
// answer 4
//===========================================
Here is the code that Reto Meier used in the google i/o presentation this year to get a unique id for the user:

复制代码
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";

public synchronized static String id(Context context) {
    if (uniqueID == null) {
        SharedPreferences sharedPrefs = context.getSharedPreferences(
                PREF_UNIQUE_ID, Context.MODE_PRIVATE);
        uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
        if (uniqueID == null) {
            uniqueID = UUID.randomUUID().toString();
            Editor editor = sharedPrefs.edit();
            editor.putString(PREF_UNIQUE_ID, uniqueID);
            editor.commit();
        }
    }
    return uniqueID;
}
复制代码

If you couple this with a backup strategy to send preferences to the cloud (also described in Reto's talk, you should have an id that ties to a user and sticks around after the device has been wiped, or even replaced. I plan to use this in analytics going forward (in other words I have not done that bit yet :).
----------------------------------------------------------------
Great answer, this should go the top. – Kiran Ryali Dec 16 '11 at 5:13
    
I was using @Lenn Dolling's method with current time appended for unique id. But this seems like more simpler and reliable way. Thanks Reto Meier and Antony Nolan – Gökhan Barış Aker Jan 3 at 13:55
    
It is great but what about rooted devices? They can access this and change uid to a different one easily. – tasomaniac May 9 at 21:25
    
Great option if you don't need the unique ID to persist after an uninstall and reinstall (e.g. promotional event/game where you get three chances to win, period). – Kyle May 15 at 21:52
//===========================================
// answer 5
//===========================================
The official Android Developers Blog now has a full article just about this very subject:

http://android-developers.blogspot.com/2011/03/identifying-app-installations.html
-------------------------------------------------------------------
And the key point of that argument is that if you're trying to get a unique ID out of the hardware, you're probably making a mistake. – Tim Bray Apr 12 '11 at 4:57

And if you're allowing your device-lock to be reset by a factory reset, your trialware model is as good as dead. – Seva Alekseyev May 4 '11 at 18:54
//===========================================
// answer 6
//===========================================
There’s rather useful info here.

It covers five different ID types:

   1. IMEI (only for Android devices with Phone use; needs android.permission.READ_PHONE_STATE)
   2. Pseudo-Unique ID (for all Android devices)
   3. Android ID (can be null, can change upon factory reset, can be altered on rooted phone)
   4. WLAN MAC Address string (needs android.permission.ACCESS_WIFI_STATE)
   5. BT MAC Address string (devices with Bluetooth, needs android.permission.BLUETOOTH)
-------------------------------------------------------------------
very useful article thanks! – Jorgesys Feb 9 at 2:26
    
your thanks go to Radu Motisan who posted original article I quoted :) – stansult Mar 14 at 1:50
//===========================================
// answer 7
//===========================================

复制代码
String serial = null;

try {
    Class<?> c = Class.forName("android.os.SystemProperties");
    Method get = c.getMethod("get", String.class);
    serial = (String) get.invoke(c, "ro.serialno");
} catch (Exception ignored) {
}
复制代码

This code returns device serial number using hidden Android API. But, this code don't works on Samsung Galaxy Tab because "ro.serialno" isn't set on this device.
------------------------------------------------------------------
I just read on xda developer that the ro.serialno is used to generate the Settings.Secure.ANDROID_ID. So they are basically different representations of the same value. – Martin Jun 23 '11 at 6:31
    
@Martin: but probably serial number doesn't change on resetting the device. Isn't it? Just a new value for ANDROID_ID is derived from it. – userSeven7s Sep 17 '11 at 8:28
    
Actually on all devices I have tested they where the identical same. Or at least the hash values where the same (for privacy reasons I do not write the true values to the log files). – Martin Sep 18 '11 at 11:53
//===========================================
// answer 8
//===========================================
I think this is sure fire way of building a skeleton for a unique ID... check it out.

Pseudo-Unique ID, that works on all Android devices Some devices don't have a phone (eg. Tablets) or for some reason you don't want to include the READ_PHONE_STATE permission. You can still read details like ROM Version, Manufacturer name, CPU type, and other hardware details, that will be well suited if you want to use the ID for a serial key check, or other general purposes. The ID computed in this way won't be unique: it is possible to find two devices with the same ID (based on the same hardware and rom image) but the chances in real world applications are negligible. For this purpose you can use the Build class:

复制代码
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
            Build.BOARD.length()%10+ Build.BRAND.length()%10 +
            Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
            Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
            Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
            Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
            Build.TAGS.length()%10 + Build.TYPE.length()%10 +
            Build.USER.length()%10 ; //13 digits
复制代码

Most of the Build members are strings, what we're doing here is to take their length and transform it via modulo in a digit. We have 13 such digits and we are adding two more in front (35) to have the same size ID like the IMEI (15 digits). There are other possibilities here are well, just have a look at these strings. Returns something like: 355715565309247 . No special permission are required, making this approach very convenient.

(Extra info: The technique given above was copied from an article on Pocket Magic.)
------------------------------------------------------------------------
Interesting solution. It sounds like this is a situation where you really should be just hashing all that data concatenated instead of trying to come up with your own "hash" function. There are many instances where you'd get collisions even if there is substantial data that is different for each value. My recommendation: use a hash function and then transform the binary results into decimal and truncate it as needed. To do it right, though you should really use a UUID or full hash string. – Steve Pomeroy Apr 12 '11 at 16:28
    
I found that the Build.CPU_ABI and Build.MANUFACTURER are not present in all versions.. I was getting harsh build errors when running against <2.2 :) – Lenn Dolling May 15 '11 at 0:09
    
You should give credit to your sources... This has been lifted straight out of the following article: pocketmagic.net/?p=1662 – Steve Haley May 16 '11 at 12:07
    
ohh for sure... I meant too.. thanks for doing what I forgot too. whoo hoo. we got some teamwork. – Lenn Dolling May 16 '11 at 16:22 
    
This ID is open to collisions like you don't know what. It's practically guaranteed to be the same on identical devices from the same carrier. – Seva Alekseyev May 26 '11 at 20:21
//===========================================
// answer 8
//===========================================
String deviceId = Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID);

Using above code you can get a Unique device ID of Android OS Device as String.
//===========================================
// answer 9
//===========================================
A Serial field was added to the Build class in API level 9 (android 2.3). Documentation says it represents the hardware serial number. thus it should be unique, if it exists on the device.

I don't know whether it is actually supported (=not null) by all devices with API level >= 9 though.
//===========================================
// answer 10
//===========================================
For detailed instructions on how to get a Unique Identifier for each Android device your application is installed from, see this official Android Developers Blog posting:

http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

It seems the best way is for you to generate one your self upon installation and subsequently read it when the application is re-launched.

I personally find this acceptable but not ideal. No one identifier provided by Android works in all instances as most are dependent on the phone's radio states (wifi on/off, cellular on/off, bluetooth on/off). The others like Settings.Secure.ANDROID_ID must be implemented by the manufacturer and are not guaranteed to be unique.

The following is an example of writing data to an INSTALLATION file that would be stored along with any other data the application saves locally.

复制代码
public class Installation {
    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();
    }
}
复制代码

----------------------------------------------------------------------------
If you want to track app installations this is perfect. Tracking devices though is a lot trickier, and there doesn't appear to be a completely air-tight solution. – Luca Spiller Oct 3 '11 at 19:56
    
What about rooted devices? They can change this installation id easily, right? – tasomaniac May 9 at 21:24
    
Absolutely. Root can change the installation ID. You can check for root using this code block: stackoverflow.com/questions/1101380/… – Kevin May 18 at 16:52

//===========================================
// answer 11
//===========================================
ne thing I'll add - I have one of those unique situations.

Using:

deviceId = Secure.getString(this.getContext().getContentResolver(), Secure.ANDROID_ID);

Turns out that even though my Viewsonic G Tablet reports a DeviceID that is not Null, every single G Tablet reports the same number.

Makes it interesting playing "Pocket Empires" which gives you instant access to someone's account based on the "unique" DeviceID.

My device does not have a cell radio.
//===========================================
// answer 12
//===========================================
How about the IMEI. That is unique for Android or other mobile devices.
------------------------------------------------------------------------------
Not for my tablets, which don't have an IMEI since they don't connect to my mobile carrier. – Brill Pappin Jan 5 at 16:54
    
Not to mention CDMA devices which have an ESN instead of an IMEI. – David Given Jan 25 at 12:25
    
@David Given is there any CDMA with Android? – Elzo Valugi Jan 26 at 14:29
    
@BrillPappin some 3G capable tables may also have, this has to be tested. – Elzo Valugi Jan 26 at 14:31
    
Turns out TelephonyManager.getDeviceId() will return the right ID regardless what technology your phone is. Of course, it does need to have telephony hardware and have it turned on... – David Given Jan 26 at 15:16

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值