Android获取IMEI和MEID

在破解微信数据库时,需要获取手机的DeviceId,但是有时会出现打不开的情况,报出file is not a database: , while compiling: select count(*) from sqlite_master的异常,这时发现我的数据库密码和之前的不一致,对比一下发现获取的deviceId不一致导致的,难道手机的deviceId也会变来变去吗?
搜了一下资料,发现获取手机的deviceId还真没想的那么容易。一般情况我们获取手机的DeviceId也就是手机的IMEI码,一般通过如下代码。此外还需要获取READ_PHONE_STATE权限。

 

private String getPhoneIMEI() {
    TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Service.TELEPHONY_SERVICE);
    return tm.getDeviceId();
}

一个双卡手机不止一个IMEI值,全网通双卡手机有两个IMEI和一个MEID,Android6.0的API中提供了这样的方法getDeviceId(int slotIndex)

type value meaning
int PHONE_TYPE_CDMA Phone radio is CDMA
int PHONE_TYPE_GSM Phone radio is GSM

 

private String getPhoneIMEI(int slotIndex) {
    TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Service.TELEPHONY_SERVICE);
    return tm.getIMEI(slotIndex);
}

private String getPhoneMEID(int slotIndex) {
    TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Service.TELEPHONY_SERVICE);
    return tm.getMEID(slotIndex);
}

在Android5.0系统中,可以通过反射获取IMEI和MEID的值。

 

private String getIMEI(int slotId){
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Method method = clazz.getMethod("get", String.class, String.class);
            String imei = (String) method.invoke(null, "ril.gsm.imei", "");
            if(!TextUtils.isEmpty(imei)){
                String[] split = imei.split(",");
                if(split.length > slotId){
                    imei = split[slotId];
                }
                Log.d(TAG,"getIMEI imei: "+ imei);
                return imei;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
            Log.w(TAG,"getIMEI error : "+ e.getMessage());
        }
        return "";
    }
    
private String getMEID(){
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Method method = clazz.getMethod("get", String.class, String.class);

            String meid = (String) method.invoke(null, "ril.cdma.meid", "");
            if(!TextUtils.isEmpty(meid)){
                Log.d(TAG,"getMEID meid: "+ meid);
                return meid;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
            Log.w(TAG,"getMEID error : "+ e.getMessage());
        }
        return "";
    }

至于上面提到的手机deviceId改变因为之前调用tm.getDeviceId()返回的imei值,后来返回meid值导致的,什么原因导致的还没发现。

你可能感兴趣的:(cocos2dx)