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 fileuuid = 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 filetry {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 fileprefs.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;}}
public class MyBackupAgent extends BackupAgentHelper {// The name of the SharedPreferences filestatic final String PREFS = "user_preferences";
// A key to uniquely identify the set of backup datastatic final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent@Overridepublic void onCreate() {SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);addHelper(PREFS_BACKUP_KEY, helper);}}
要完成备份,您需要在主活动中创建BackupManager实例:
BackupManager backupManager = new BackupManager(context);
if API >= 9/10: (99.5% of devices)
return unique ID containing serial id (rooted devices may be different)
else
return the unique ID of build information (may overlap data - API < 9)
/*** Return pseudo unique ID* @return ID*/public static String getUniquePsuedoID() {// If all else fails, if the user does have lower than API 9 (lower// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'// returns 'null', then simply the ID returned will be solely based// off their Android device information. This is where the collisions// can happen.// Thanks http://www.pocketmagic.net/?p=1662!// Try not to use DISPLAY, HOST or ID - these items could change.// If there are collisions, there will be overlapping dataString m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to @Roman SL!// https://stackoverflow.com/a/4789483/950427// Only devices with API >= 9 have android.os.Build.SERIAL// http://developer.android.com/reference/android/os/Build.html#SERIAL// If a user upgrades software or roots their device, there will be a duplicate entryString serial = null;try {serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();} catch (Exception exception) {// String needs to be initializedserial = "serial"; // some value}
// Thanks @Joe!// https://stackoverflow.com/a/2853253/950427// Finally, combine the values we have found by using the UUID class to create a unique identifierreturn new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();}
import com.google.android.gms.ads.identifier.AdvertisingIdClient;import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;import com.google.android.gms.common.GooglePlayServicesAvailabilityException;import com.google.android.gms.common.GooglePlayServicesNotAvailableException;import java.io.IOException;...
// Do not call this function from the main thread. Otherwise,// an IllegalStateException will be thrown.public void getIdThread() {
Info adInfo = null;try {adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException exception) {// Unrecoverable error connecting to Google Play services (e.g.,// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesAvailabilityException exception) {// Encountered a recoverable error connecting to Google Play services.
} catch (GooglePlayServicesNotAvailableException exception) {// Google Play services is not available entirely.}final String id = adInfo.getId();final boolean isLAT = adInfo.isLimitAdTrackingEnabled();}
import android.Manifest.permission;import android.bluetooth.BluetoothAdapter;import android.content.Context;import android.content.pm.PackageManager;import android.net.wifi.WifiManager;import android.provider.Settings.Secure;import android.telephony.TelephonyManager;import android.util.Log;
// TODO : hashpublic final class DeviceIdentifier {
private DeviceIdentifier() {}
/** @see http://code.google.com/p/android/issues/detail?id=10603 */private static final String ANDROID_ID_BUG_MSG = "The device suffers from "+ "the Android ID bug - its ID is the emulator ID : "+ IDs.BUGGY_ANDROID_ID;private static volatile String uuid; // volatile needed - see EJ item 71// need lazy initialization to get a context
/*** Returns a unique identifier for this device. The first (in the order the* enums constants as defined in the IDs enum) non null identifier is* returned or a DeviceIDException is thrown. A DeviceIDException is also* thrown if ignoreBuggyAndroidID is false and the device has the Android ID* bug** @param ctx* an Android constant (to retrieve system services)* @param ignoreBuggyAndroidID* if false, on a device with the android ID bug, the buggy* android ID is not returned instead a DeviceIDException is* thrown* @return a *device* ID - null is never returned, instead a* DeviceIDException is thrown* @throws DeviceIDException* if none of the enum methods manages to return a device ID*/public static String getDeviceIdentifier(Context ctx,boolean ignoreBuggyAndroidID) throws DeviceIDException {String result = uuid;if (result == null) {synchronized (DeviceIdentifier.class) {result = uuid;if (result == null) {for (IDs id : IDs.values()) {try {result = uuid = id.getId(ctx);} catch (DeviceIDNotUniqueException e) {if (!ignoreBuggyAndroidID)throw new DeviceIDException(e);}if (result != null) return result;}throw new DeviceIDException();}}}return result;}
private static enum IDs {TELEPHONY_ID {
@OverrideString getId(Context ctx) {// TODO : add a SIM based mechanism ? tm.getSimSerialNumber();final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);if (tm == null) {w("Telephony Manager not available");return null;}assertPermission(ctx, permission.READ_PHONE_STATE);return tm.getDeviceId();}},ANDROID_ID {
@OverrideString getId(Context ctx) throws DeviceIDException {// no permission needed !final String andoidId = Secure.getString(ctx.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);if (BUGGY_ANDROID_ID.equals(andoidId)) {e(ANDROID_ID_BUG_MSG);throw new DeviceIDNotUniqueException();}return andoidId;}},WIFI_MAC {
@OverrideString getId(Context ctx) {WifiManager wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);if (wm == null) {w("Wifi Manager not available");return null;}assertPermission(ctx, permission.ACCESS_WIFI_STATE); // I guess// getMacAddress() has no java doc !!!return wm.getConnectionInfo().getMacAddress();}},BLUETOOTH_MAC {
@OverrideString getId(Context ctx) {BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();if (ba == null) {w("Bluetooth Adapter not available");return null;}assertPermission(ctx, permission.BLUETOOTH);return ba.getAddress();}}// TODO PSEUDO_ID// http://www.pocketmagic.net/2011/02/android-unique-device-id/;
static final String BUGGY_ANDROID_ID = "9774d56d682e549c";private final static String TAG = IDs.class.getSimpleName();
abstract String getId(Context ctx) throws DeviceIDException;
private static void w(String msg) {Log.w(TAG, msg);}
private static void e(String msg) {Log.e(TAG, msg);}}
private static void assertPermission(Context ctx, String perm) {final int checkPermission = ctx.getPackageManager().checkPermission(perm, ctx.getPackageName());if (checkPermission != PackageManager.PERMISSION_GRANTED) {throw new SecurityException("Permission " + perm + " is required");}}
// =========================================================================// Exceptions// =========================================================================public static class DeviceIDException extends Exception {
private static final long serialVersionUID = -8083699995384519417L;private static final String NO_ANDROID_ID = "Could not retrieve a "+ "device ID";
public DeviceIDException(Throwable throwable) {super(NO_ANDROID_ID, throwable);}
public DeviceIDException(String detailMessage) {super(detailMessage);}
public DeviceIDException() {super(NO_ANDROID_ID);}}
public static final class DeviceIDNotUniqueException extendsDeviceIDException {
private static final long serialVersionUID = -8940090896069484955L;
public DeviceIDNotUniqueException() {super(ANDROID_ID_BUG_MSG);}}}
List<NetworkInterface> interfacesList = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface interface : interfacesList) {// This will give you the interface MAC ADDRESSinterface.getHardwareAddress();}
import android.telephony.TelephonyManager;import android.content.Context;// ...TelephonyManager telephonyManager;telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);/** getDeviceId() returns the unique device ID.* For example,the IMEI for GSM and the MEID or ESN for CDMA phones.*/String deviceId = telephonyManager.getDeviceId();/** getSubscriberId() returns the unique subscriber ID,*/String subscriberId = telephonyManager.getSubscriberId();
FirebaseInstallations.getInstance().getId().addOnCompleteListener(task -> {if (task.isSuccessful()) {String firebaseIdentifier = task.getResult();// Do what you need with firebaseIdentifier}});
package com.aapbd.appbajarlib.common;
import android.os.Build;
import java.util.Locale;import java.util.UUID;
public class DeviceID {
public static String getDeviceLanguage(){
Locale locale=Locale.getDefault();return locale.getDisplayLanguage();
}
public static String getDeviceCountry(){
Locale locale=Locale.getDefault();return locale.getDisplayCountry();
}
public static String getDeviceName() {String manufacturer = Build.MANUFACTURER;String model = Build.MODEL;if (model.startsWith(manufacturer)) {return capitalize(model);} else {return capitalize(manufacturer) + " " + model;}}
public static String getAndroidVersion() {
String release = Build.VERSION.RELEASE;int sdkVersion = Build.VERSION.SDK_INT;return sdkVersion + " (" + release +")";
}
public static int getAndroidAPILevel() {
int sdkVersion = Build.VERSION.SDK_INT;return sdkVersion;
}
private static String capitalize(String s) {if (s == null || s.length() == 0) {return "";}char first = s.charAt(0);if (Character.isUpperCase(first)) {return s;} else {return Character.toUpperCase(first) + s.substring(1);}}
/*** Return pseudo unique ID* @return ID*/public static String getUniquePsuedoID() {// If all else fails, if the user does have lower than API 9 (lower// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'// returns 'null', then simply the ID returned will be solely based// off their Android device information. This is where the collisions// can happen.// Thanks http://www.pocketmagic.net/?p=1662!// Try not to use DISPLAY, HOST or ID - these items could change.// If there are collisions, there will be overlapping dataString m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to @Roman SL!// http://stackoverflow.com/a/4789483/950427// Only devices with API >= 9 have android.os.Build.SERIAL// http://developer.android.com/reference/android/os/Build.html#SERIAL// If a user upgrades software or roots their device, there will be a duplicate entryString serial = null;try {serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();} catch (Exception exception) {// String needs to be initializedserial = "serial"; // some value}
// Thanks @Joe!// http://stackoverflow.com/a/2853253/950427// Finally, combine the values we have found by using the UUID class to create a unique identifierreturn new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();}
}