Android设备的唯一ID

关于本文档

Android的开发者在一些特定情况下都需要知道手机中的唯一设备ID例如,跟踪应用程序的安装,生成用于复制保护的DRM时需要使用设备的唯一ID在本文档结尾处提供了作为参考的示例代码片段。

范围

本文提供有关如何读取各种Android设备的 ID的介绍,用以使用标识号。本文假定用户已经安装了Android以及开发应用程序必要的工具。并且,本文假定用户已了解Android的基本知识。

简介在搭载Android操作系统的设备中,已经存在好几种类型的设备标识号。先前的所有Android设备都具有电话功能,因此查找每部设备硬件唯一的IMEIMEID,或ESN也很容易。但仅能使用Wifi的设备或音乐播放器没有电话硬件,所以没有这种类型的唯一标识号。本文阐述了如何读取不同Android设备的标识号。检索Android设备ID各种方式

以下是Android设备不同类型的识别设备ID

· 唯一编号(IMEIMEIDESNIMSI

· MAC地址

· 序列号

· ANDROID_ID

 

唯一编号(IMEIMEIDESNIMSI

说明在以前,当Android设备均作为电话使用时,寻找唯一标识号比较简单:()可用于找到(取决于网络技术)手机硬件唯一的IMEIMEIDESNIMSI编号。

TelephonyManager.getDeviceId

IMEIMEIDESNIMSI的定义如下:

•IMEI(国际移动设备识别码)唯一编号,用于识别 GSMWCDMA手机以及一些卫星电话(移动设备识别码)全球唯一编号,用于识别CDMA移动电台设备的物理硬件,MEID出现的目的是取代ESN号段(电子序列号)(电子序列号)唯一编号,用于识别CDMA手机(国际移动用户识别码)与所有GSMUMTS网络手机用户相关联的唯一识别编号如需要检索设备的ID,在项目中要使用以下代码:

•MEID

•ESN

•IMSI

[java]  view plain copy
  1. import android.telephony.TelephonyManager;  
  2.   
  3. import android.content.Context;  
  4.   
  5. String imeistring = null;  
  6. String imsistring = null;  
  7.     {  
  8.         TelephonyManager    telephonyManager;  
  9.         telephonyManager =  
  10.             (TelephonyManager) getSystemService( Context.TELEPHONY_SERVICE );  
  11.   
  12.         /* 
  13.          * getDeviceId() function Returns the unique device ID. 
  14.          * for example,the IMEI for GSM and the MEID or ESN for CDMA phones. 
  15.          */                                                                
  16.         imeistring = telephonyManager.getDeviceId();  
  17.         /* 
  18.         * getSubscriberId() function Returns the unique subscriber ID, 
  19.         * for example, the IMSI for a GSM phone. 
  20.         */  
  21.         imsistring = telephonyManager.getSubscriberId();  
  22.     }  

如要只读取手机的状态,则需添加READ_PHONE_STATE许可到AndroidManifest.xml文件中。

<uses-permission

  android:name="android.permission.READ_PHONE_STATE" >

</uses-permission>

缺点

•Android设备要具有电话功能

其工作不是很可靠

序列号

当其工作时,该值保留了设备的重置信息(恢复出厂设置),从而可以消除当客户删除自己设备上的信息,并把设备转另一个人时发生的错误。

Mac地址

说明

可通过检索找到设备的Wi - Fi或蓝牙硬件的Mac地址。但是,不推荐使用Mac地址作为唯一的标识号。

缺点设备要具备Wi – Fi功能(并非所有的设备都有Wi – Fi功能)如果设备目前正在使用Wi - Fi,则不能报告Mac地址

序列号

Android 2.3姜饼)开始,通过android.os.Build.SERIAL方法序列号可被使用。没有电话功能的设备也都需要上给出唯一的设备ID;  某些手机也可以需要这样做。序列号可以用于识别MID(移动互联网设备)或PMP(便携式媒体播放器),这两种设备都没有电话功能。通过读取系统属性值“ro.serialno”的方法,可以使用序列号作为设备ID 如检索序列号并作为设备ID使用,请参考下面的代码示例。

[java]  view plain copy
  1. <span style="font-size:16px;">import java.lang.reflect.Method;  
  2.   
  3. String serialnum = null;  
  4.   
  5.     try {  
  6.         Class<?> c = Class.forName("android.os.SystemProperties");  
  7.         Method get = c.getMethod("get", String.class, String.class );  
  8.         serialnum = (String)(   get.invoke(c, "ro.serialno""unknown" )  );  
  9.     } catch (Exception ignored) {                                
  10.     }</span>  

缺点

序列号无法在所有Android设备上使用。

ANDROID_ID

 

说明

更具体地说,Settings.Secure.ANDROID_ID 是一串64位的编码(十六进制的字符串),是随机生成的设备的第一个引导,其记录着一个固定值,通过它可以知道设备的寿命(在设备恢复出厂设置后,该值可能会改变)。 ANDROID_ID也可视为作为唯一设备标识号的一个好选择。如要检索用于设备ID ANDROID_ID,请参阅下面的示例代码

String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);

 

缺点

• 对于Android 2.2“Froyo”)之前的设备不是100%的可靠

• 此外,在主流制造商的畅销手机中至少存在一个众所周知的错误,每一个实例都具有相同的ANDROID_ID 

 

结论

对于绝大多数应用来说,只需识别特定的安装配置,而不需要识别物理设备。所幸是,这样做就省去了麻烦。

下面是部分使用设备ID的最佳途径:

支持各种设备类型的另一种方法是使用getDeviceID()APIro.serialno的组合

有许多值得参考的原因,来提醒开发者避免试图识别特定的设备。对于那些想做一下这方面尝试的用户, 最好的办法可能是使用ANDROID_ID,并在一些传统设备上做尝试。

示例代码

下面是用于追踪Android设置的示例代码

: ReadDeviceID.java

[java]  view plain copy
  1. <span xmlns="http://www.w3.org/1999/xhtml" style="font-size:12px;color:#000000;"><strong xmlns="http://www.w3.org/1999/xhtml"><span xmlns="http://www.w3.org/1999/xhtml" style="">package com.deviceid;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.os.Bundle;  
  8. import android.provider.Settings;  
  9. import android.telephony.TelephonyManager;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.TextView;  
  14.   
  15. public class ReadDeviceID extends Activity {  
  16.   
  17.     Button bt;  
  18.     TextView idView;  
  19.     /** Called when the activity is first created. */  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         bt=(Button)findViewById(R.id.button1);  
  25.         idView=(TextView)findViewById(R.id.textView1);  
  26.         bt.setOnClickListener(new OnClickListener() {  
  27.             @Override  
  28.             public void onClick(View v) {  
  29.                 String imeistring=null;  
  30.                 String imsistring=null;  
  31.                 TelephonyManager   telephonyManager =  
  32.                     ( TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );  
  33.                 /* 
  34.                  * getDeviceId() function Returns the unique device ID. 
  35.                  * for example,the IMEI for GSM and the MEID or ESN for CDMA phones. 
  36.                  */  
  37.                 imeistring = telephonyManager.getDeviceId();  
  38.                 idView.append("IMEI No : "+imeistring+"\n");  
  39.                 /* 
  40.                  * getSubscriberId() function Returns the unique subscriber ID, 
  41.                  * for example, the IMSI for a GSM phone. 
  42.                  */  
  43.                 imsistring = telephonyManager.getSubscriberId();  
  44.                 idView.append("IMSI No : "+imsistring+"\n");  
  45.                 /* 
  46.                  * System Property ro.serialno returns the serial number as unique number 
  47.                  * Works for Android 2.3 and above         
  48.                  */  
  49.                 String hwID = android.os.SystemProperties.get("ro.serialno""unknown");  
  50.                 idView.append( "hwID : " + hwID + "\n" );  
  51.                 String serialnum = null;  
  52.                 try {  
  53.                     Class<?> c = Class.forName("android.os.SystemProperties");  
  54.                     Method get = c.getMethod("get", String.class, String.class );  
  55.                     serialnum = (String)(   get.invoke(c, "ro.serialno""unknown" )  );  
  56.                     idView.append( "serial : " + serialnum + "\n" );  
  57.                 } catch (Exception ignored) {  
  58.                 }  
  59.                 String serialnum2 = null;  
  60.                 try {  
  61.                     Class myclass = Class.forName( "android.os.SystemProperties" );  
  62.                     Method[] methods = myclass.getMethods();  
  63.                     Object[] params = new Object[] { new String( "ro.serialno" ) , new String("Unknown" ) };  
  64.                     serialnum2 = (String)(methods[2].invoke( myclass, params ));  
  65.                     idView.append( "serial2 : " + serialnum2 + "\n" );  
  66.                 }catch (Exception ignored) {  
  67.                       
  68.                 }  
  69.                 /* 
  70.                  * Settings.Secure.ANDROID_ID returns the unique DeviceID 
  71.                  * Works for Android 2.2 and above         
  72.                  */  
  73.                 String androidId = Settings.Secure.getString(getContentResolver(),  
  74.                         Settings.Secure.ANDROID_ID);  
  75.                 idView.append( "AndroidID : " + androidId + "\n" );  
  76.             }  
  77.         });  
  78.     }  
  79. } </span></strong></span>  

: SystemProperties.java

[java]  view plain copy
  1. package android.os;  
  2.   
  3. /** 
  4.  * Gives access to the system properties store. The system properties 
  5.  * store contains a list of string key-value pairs. 
  6.  * 
  7.  * {@hide} 
  8.  */  
  9. public class SystemProperties {  
  10.     public static final int PROP_NAME_MAX = 31;  
  11.     public static final int PROP_VALUE_MAX = 91;  
  12.     private static native String native_get(String key);  
  13.     private static native String native_get(String key, String def);  
  14.     private static native int native_get_int(String key, int def);  
  15.     private static native long native_get_long(String key, long def);  
  16.     private static native boolean native_get_boolean(String key, boolean def);  
  17.     private static native void native_set(String key, String def);  
  18.   
  19.     /** 
  20.      * Get the value for the given key. 
  21.      * @return an empty string if the key isn't found 
  22.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  23.      */  
  24.     public static String get(String key) {  
  25.         if (key.length() > PROP_NAME_MAX) {  
  26.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  27.         }  
  28.         return native_get(key);  
  29.     }  
  30.   
  31.     /** 
  32.      * Get the value for the given key. 
  33.      * @return if the key isn't found, return def if it isn't null, or an empty string otherwise 
  34.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  35.      */  
  36.     public static String get(String key, String def) {  
  37.         if (key.length() > PROP_NAME_MAX) {  
  38.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  39.         }  
  40.         return native_get(key, def);  
  41.     }  
  42.   
  43.     /** 
  44.      * Get the value for the given key, and return as an integer. 
  45.      * @param key the key to lookup 
  46.      * @param def a default value to return 
  47.      * @return the key parsed as an integer, or def if the key isn't found or 
  48.      *         cannot be parsed 
  49.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  50.      */  
  51.     public static int getInt(String key, int def) {  
  52.         if (key.length() > PROP_NAME_MAX) {  
  53.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  54.         }  
  55.         return native_get_int(key, def);  
  56.     }  
  57.   
  58.     /** 
  59.      * Get the value for the given key, and return as a long. 
  60.      * @param key the key to lookup 
  61.      * @param def a default value to return 
  62.      * @return the key parsed as a long, or def if the key isn't found or 
  63.      *         cannot be parsed 
  64.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  65.      */  
  66.     public static long getLong(String key, long def) {  
  67.         if (key.length() > PROP_NAME_MAX) {  
  68.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  69.         }  
  70.         return native_get_long(key, def);  
  71.     }  
  72.   
  73.     /** 
  74.      * Get the value for the given key, returned as a boolean. 
  75.      * Values 'n', 'no', '0', 'false' or 'off' are considered false. 
  76.      * Values 'y', 'yes', '1', 'true' or 'on' are considered true. 
  77.      * (case insensitive). 
  78.      * If the key does not exist, or has any other value, then the default 
  79.      * result is returned. 
  80.      * @param key the key to lookup 
  81.      * @param def a default value to return 
  82.      * @return the key parsed as a boolean, or def if the key isn't found or is 
  83.      *         not able to be parsed as a boolean. 
  84.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  85.      */  
  86.     public static boolean getBoolean(String key, boolean def) {  
  87.         if (key.length() > PROP_NAME_MAX) {  
  88.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  89.         }  
  90.         return native_get_boolean(key, def);  
  91.     }  
  92.   
  93.     /** 
  94.      * Set the value for the given key. 
  95.      * @throws IllegalArgumentException if the key exceeds 32 characters 
  96.      * @throws IllegalArgumentException if the value exceeds 92 characters 
  97.      */  
  98.     public static void set(String key, String val) {  
  99.         if (key.length() > PROP_NAME_MAX) {  
  100.             throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);  
  101.         }  
  102.         if (val != null && val.length() > PROP_VALUE_MAX) {  
  103.             throw new IllegalArgumentException("val.length > " +  
  104.                 PROP_VALUE_MAX);  
  105.         }  
  106.         native_set(key, val);  
  107.     }  
  108. }  

使用"ReadDeviceID" activity 创建"com.deviceid"项目。将布局"main.xml"改写成下面的代码

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

<Button

    android:text="GetDeviceID"

    android:id="@+id/button1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content">

</Button>

<TextView    

    android:id="@+id/textView1"   

    android:layout_width="fill_parent"

    android:layout_height="wrap_content">

</TextView>

</LinearLayout>

"AndroidManifest.xml"文件中添加"READ_PHONE_STATE"许可,使应用程序可以登陆互联网。

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.deviceid"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="7" />

 

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".ReadDeviceID"

                  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

 

    </application>

  

    <uses-permission

            android:name="android.permission.READ_PHONE_STATE" >

      </uses-permission>

   

</manifest>

 

转载于:https://my.oschina.net/u/266323/blog/180068

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值