当前位置: 移动技术网 > 移动技术>移动开发>Android > 浅谈android获取设备唯一标识完美解决方案

浅谈android获取设备唯一标识完美解决方案

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文介绍了浅谈android获取设备唯一标识完美解决方案,分享给大家,具体如下:

/**
 * deviceid的组成为:渠道标志+识别符来源标志+hash后的终端识别符 
 * 
 * 渠道标志为: 
 * 1,andriod(a) 
 * 
 * 识别符来源标志: 
 * 1, wifi mac地址(wifi); 
 * 2, imei(imei); 
 * 3, 序列号(sn); 
 * 4, id:随机码。若前面的都取不到时,则随机生成一个随机码,需要缓存。 
 * 
 * @param context 
 * @return 
 */ 
public static string getdeviceid(context context) { 
 stringbuilder deviceid = new stringbuilder(); 
 // 渠道标志 
 deviceid.append("a"); 
 try { 
  //wifi mac地址 
  wifimanager wifi = (wifimanager) context.getsystemservice(context.wifi_service); 
  wifiinfo info = wifi.getconnectioninfo(); 
  string wifimac = info.getmacaddress(); 
  if(!isempty(wifimac)){ 
   deviceid.append("wifi"); 
   deviceid.append(wifimac); 
   palog.e("getdeviceid : ", deviceid.tostring()); 
   return deviceid.tostring(); 
  } 
  //imei(imei) 
  telephonymanager tm = (telephonymanager) context.getsystemservice(context.telephony_service); 
  string imei = tm.getdeviceid(); 
  if(!isempty(imei)){ 
   deviceid.append("imei"); 
   deviceid.append(imei); 
   palog.e("getdeviceid : ", deviceid.tostring()); 
   return deviceid.tostring(); 
  } 
  //序列号(sn) 
  string sn = tm.getsimserialnumber(); 
  if(!isempty(sn)){ 
   deviceid.append("sn"); 
   deviceid.append(sn); 
   palog.e("getdeviceid : ", deviceid.tostring()); 
   return deviceid.tostring(); 
  } 
  //如果上面都没有, 则生成一个id:随机码 
  string uuid = getuuid(context); 
  if(!isempty(uuid)){ 
   deviceid.append("id"); 
   deviceid.append(uuid); 
   palog.e("getdeviceid : ", deviceid.tostring()); 
   return deviceid.tostring(); 
  } 
 } catch (exception e) { 
  e.printstacktrace(); 
  deviceid.append("id").append(getuuid(context)); 
 } 
 palog.e("getdeviceid : ", deviceid.tostring()); 
 return deviceid.tostring(); 
} 
/** 
 * 得到全局唯一uuid 
 */ 
public static string getuuid(context context){ 
 sharedpreferences mshare = getsysshare(context, "syscachemap"); 
 if(mshare != null){ 
  uuid = mshare.getstring("uuid", ""); 
 } 
 if(isempty(uuid)){ 
  uuid = uuid.randomuuid().tostring(); 
  savesysmap(context, "syscachemap", "uuid", uuid); 
 } 
 palog.e(tag, "getuuid : " + uuid); 
return uuid; 
} 

有时需要对用户设备进行标识,所以希望能够得到一个稳定可靠并且唯一的识别码。虽然android系统中提供了这样设备识别码,但是由于android系统版本、厂商定制系统中的bug等限制,稳定性和唯一性并不理想。而通过其他硬件信息标识也因为系统版本、手机硬件等限制存在不同程度的问题。

下面收集了一些“有能力”或“有一定能力”作为设备标识的串码。

device_id

这是android系统为开发者提供的用于标识手机设备的串号,也是各种方法中普适性较高的,可以说几乎所有的设备都可以返回这个串号,并且唯一性良好。

这个device_id可以同通过下面的方法获取:

telephonymanager tm = (telephonymanager)getsystemservice(context.telephony_service); 
string device_id = tm.getdeviceid();  

假设我们确实需要用到真实设备的标识,可能就需要用到device_id。在以前,我们的android设备是手机,这个device_id可以同通过telephonymanager.getdeviceid()获取,它根据不同的手机设备返回imei,meid或者esn码,但它在使用的过程中会遇到很多问题:

  • 非手机设备: 如果只带有wifi的设备或者音乐播放器没有通话的硬件功能的话就没有这个device_id
  • 权限: 获取device_id需要read_phone_state权限,但如果我们只为了获取它,没有用到其他的通话功能,那这个权限有点大才小用
  • bug:在少数的一些手机设备上,该实现有漏洞,会返回垃圾,如:zeros或者asterisks的产品

mac address

可以使用手机wifi或蓝牙的mac地址作为设备标识,但是并不推荐这么做,原因有以下两点:

  • 硬件限制:并不是所有的设备都有wifi和蓝牙硬件,硬件不存在自然也就得不到这一信息。
  • 获取的限制:如果wifi没有打开过,是无法获取其mac地址的;而蓝牙是只有在打开的时候才能获取到其mac地址。

获取wifi mac地址:

获取蓝牙 mac地址:

sim serial number

装有sim卡的android 2.3设备,可以通过下面的方法获取到sim serial number:

telephonymanager tm = (telephonymanager)getsystemservice(context.telephony_service);  
string simserialnumber = tm.getsimserialnumber();  

注意:对于cdma设备,返回的是一个空值!

android_id

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

import android.provider.settings; 
string android_id = settings.system.getstring(getcontentresolver(), settings.system.android_id); 

android_id可以作为设备标识,但需要注意:

  • 厂商定制系统的bug:不同的设备可能会产生相同的android_id:9774d56d682e549c。
  • 厂商定制系统的bug:有些设备返回的值为null。
  • 设备差异:对于cdma设备,android_id和telephonymanager.getdeviceid() 返回相同的值。
  • 它在android <=2.1 or android >=2.3的版本是可靠、稳定的,但在2.2的版本并不是100%可靠的

serial number

android系统2.3版本以上可以通过下面的方法得到serial number,且非手机设备也可以通过该接口获取。

string serialnumber = android.os.build.serial;  

以上几种方式都或多或少存在一定的局限性或者bug,如果并不是确实需要对硬件本身进行绑定,使用自己生成的uuid也是一个不错的选择,因为该方法无需访问设备的资源,也跟设备类型无关。

installtion id

这种方式的原理是在程序安装后第一次运行时生成一个id,该方式和设备唯一标识不一样,不同的应用程序会产生不同的id,同一个程序重新安装也会不同。所以这不是设备的唯一id,但是可以保证每个用户的id是不同的。可以说是用来标识每一份应用程序的唯一id(即installtion id),可以用来跟踪应用的安装数量等。

google developer blog提供了这样的一个框架:

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(); 
  } 
} 

设备唯一id

上文可以看出,android系统中并没有可以可靠获取所有厂商设备唯一id的方法,各个方法都有自己的使用范围和局限性,这也是目前流行的android系统版本过多,设备也是来自不同厂商,且没有统一标准等原因造成的。

从目前发展来看,android系统多版本共存还会持续较长的时间,而android系统也不会被某个设备生产厂商垄断,长远看android基础系统将会趋于稳定,设备标识也将会作为系统基础部分而标准化,届时这一问题才有望彻底解决。

目前的解决办法,比较可行的是一一适配,在保证大多数设备方便的前提下,如果获取不到,使用其他备选信息作为标识,即自己再封装一个设备id出来,通过内部算法保证尽量和设备硬件信息相关,以及标识的唯一性。

总结

综合以上所述,为了实现在设备上更通用的获取设备唯一标识,我们可以实现这样的一个类,为每个设备产生唯一的uuid,以android_id为基础,在获取失败时以telephonymanager.getdeviceid()为备选方法,如果再失败,使用uuid的生成策略。

重申下,以下方法是生成device id,在大多数情况下installtion id能够满足我们的需求,但是如果确实需要用到device id,那可以通过以下方式实现:

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 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; 
  } 
} 

如何获取android手机的唯一标识?

代码: 这里是你在android里读出 唯一的 imsi-id / imei-id 的方法。

java:

string myimsi = android.os.systemproperties.get(android.telephony.telephonyproperties.property_imsi);  
// within my emulator it returns: 310995000000000  
 
string myimei = android.os.systemproperties.get(android.telephony.telephonyproperties.property_imei);  
// within my emulator it returns: 000000000000000  

注:android.os.systemproperties的标签被打上@hide了,所以sdk中并不会存在。如果需要使用,需要有android的source code支持。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网