Android端获取手机IMEI,IMSI, MAC等授信功能的工具类,还包括屏幕宽高,屏幕亮度,网络类型判断等

现在app开发一般要获取手机上的授权信息,包括:

手机型号,手机制造商,系统类型,操作系统版本,安卓id,imei,imsi,mac,网络类型,无线网络名称,无线BSSID,是否root,屏幕宽,屏幕高等等

一般是以json加载请求头

JSONObject object = new JSONObject();

object.put("mp_model=" ,PhoneInfoUtil.getSystemModel());//手机型号
object.put("mp_manufacturer=",PhoneInfoUtil.getDeviceBrand());//手机制造厂商
object.put("mp_sys_type=","Android");//系统类型
object.put("mp_sys_version=",PhoneInfoUtil.getOsInfo());//操作系统版本
object.put("android_id=",PhoneInfoUtil.getUniquePsuedoID());//安卓id
object.put("imei=",PhoneInfoUtil.getIMEI(mContext));//imei
object.put("imsi=",PhoneInfoUtil.getIMSI(mContext));//imsi
object.put("mac=",PhoneInfoUtil.getLocalMacAddressFromIp());//mac
object.put("network_type=",NetWorkUtils.GetNetworkType(mContext));//网络类型
object.put("wifi_name=",PhoneInfoUtil.getSsid(mContext));//无线网络名称
object.put("wifi_bssid=",PhoneInfoUtil.getBssid(mContext));//无线BSSID
object.put("root_flag=",PhoneInfoUtil.getUniquePsuedoID());//是否root
object.put("width=",WindowUtil.getWindowsWidth(mContext));//屏幕宽
object.put("height=",WindowUtil.getWindowsHeight(mContext));//屏幕高

现在我将附上工具类,以省去大家的搜索时间

PhoneInfoUtil工具类,获取手机的基本信息以及通讯录的获取

NetWorkUtils工具类,判断网络类型2G,3G,4G,wifi等

WindowUtil工具类,屏幕宽高,屏幕亮度,px和dp相互转换,屏幕背景的透明度等

 

/**
 * 系统信息工具
 * Created by lk
 */
public class PhoneInfoUtil {

    /**
     * 得到操作系统的信息
     */
    public static final String getOsInfo() {
        return Build.VERSION.RELEASE;
    }



    //获得独一无二的Psuedo ID
    public static String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                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 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }


    public static String getVersionName(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }


    public static String size(long size) {
        if (size / (1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return "" + df.format(tmpSize) + "MB";
        } else if (size / 1024 > 0) {
            return "" + (size / (1024)) + "KB";
        } else
            return "" + size + "B";
    }

    /*
     * 得到当前app系统版本号
     * */
    public static String getCurrentVersion(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        String version = "";
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static int getCurrentVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int versioncode = packInfo.versionCode;
            return versioncode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取手机IMEI
     *
     * @param context
     * @return
     */
    public static final String getIMEI(Context context) {
        try {

            //实例化TelephonyManager对象
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = "";
            //判断系统是否是在6.0以上
            if (Build.VERSION.SDK_INT >= 23) {
                //判断是否有读写权限,如果等于PERMISSION_GRANTED就代表有
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                        ) {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE}
                            , 11);
                } else {
                    //获取IMEI号
                    imei = telephonyManager.getDeviceId();
                    //在次做个验证,也不是什么时候都能获取到的啊
                    if (imei == null) {
                        imei = "";
                    }

                }
            } else {
                //获取IMEI号
                imei = telephonyManager.getDeviceId();
                //在次做个验证,也不是什么时候都能获取到的啊
                if (imei == null) {
                    imei = "";
                }
            }

            return imei;


        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 获取手机IMSI
     */
    public static String getIMSI(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imsi = "";
            //判断系统是否是在6.0以上
            if (Build.VERSION.SDK_INT >= 23) {
                //判断是否有读写权限,如果等于PERMISSION_GRANTED就代表有
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                        ) {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE}
                            , 11);
                } else {
                    //获取IMEI号
                    imsi = telephonyManager.getSubscriberId();
                    //在次做个验证,也不是什么时候都能获取到的啊
                    if (imsi == null) {
                        imsi = "";
                    }

                }
            } else {
                //获取IMEI号
                imsi = telephonyManager.getSubscriberId();
                //在次做个验证,也不是什么时候都能获取到的啊
                if (imsi == null) {
                    imsi = "";
                }
            }

            return imsi;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }


    /**
     * 获取当前手机系统语言。(待定)
     *
     * @return 返回当前系统语言。例如:当前设置的是“中文-中国”,则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }


    /**
     * 判断手机是否root,不弹出root请求框
*/ public static boolean isRoot() { String binPath = "/system/bin/su"; String xBinPath = "/system/xbin/su"; if (new File(binPath).exists() && isExecutable(binPath)) return true; if (new File(xBinPath).exists() && isExecutable(xBinPath)) return true; return false; } private static boolean isExecutable(String filePath) { Process p = null; try { p = Runtime.getRuntime().exec("ls -l " + filePath); // 获取返回内容 BufferedReader in = new BufferedReader(new InputStreamReader( p.getInputStream())); String str = in.readLine(); if (str != null && str.length() >= 4) { char flag = str.charAt(3); if (flag == 's' || flag == 'x') return true; } } catch (IOException e) { e.printStackTrace(); } finally { if (p != null) { p.destroy(); } } return false; } /** * 根据IP地址获取MAC地址 * * @return */ public static String getLocalMacAddressFromIp() { String strMacAddr = null; try { //获得IpD地址 InetAddress ip = getLocalInetAddress(); byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < b.length; i++) { if (i != 0) { buffer.append(':'); } String str = Integer.toHexString(b[i] & 0xFF); buffer.append(str.length() == 1 ? 0 + str : str); } strMacAddr = buffer.toString().toUpperCase(); } catch (Exception e) { } return strMacAddr; } /** * 获取移动设备本地IP * * @return */ private static InetAddress getLocalInetAddress() { InetAddress ip = null; try { //列举 Enumeration en_netInterface = NetworkInterface.getNetworkInterfaces(); while (en_netInterface.hasMoreElements()) {//是否还有元素 NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素 Enumeration en_ip = ni.getInetAddresses();//得到一个ip地址的列举 while (en_ip.hasMoreElements()) { ip = en_ip.nextElement(); if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) break; else ip = null; } if (ip != null) { break; } } } catch (SocketException e) { e.printStackTrace(); } return ip; } /* * 获取bssid * */ public static String getBssid(Context context) { String bssid = ""; //判断系统是否是在6.0以上 if (Build.VERSION.SDK_INT >= 23) { //判断是否有读写权限,如果等于PERMISSION_GRANTED就代表有 if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , 10); } else { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); bssid = info.getBSSID(); } } else { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); bssid = info.getBSSID(); } return bssid; } /* * 获取ssid * */ public static String getSsid(Context context) { String ssid = ""; //判断系统是否是在6.0以上 if (Build.VERSION.SDK_INT >= 23) { //判断是否有读写权限,如果等于PERMISSION_GRANTED就代表有 if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , 10); } else { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); ssid = info.getSSID(); } } else { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); ssid = info.getSSID(); } return ssid; } /* * 获取包名 * */ public static String getPackageName()//获取版本号(内部识别号) { try { PackageInfo info = MyApplication.getInstance().getPackageManager().getPackageInfo(MyApplication.getInstance().getPackageName(), 0); // 当前版本的包名 String packageNames = info.packageName; if(StringUtilInput.isEmpty(packageNames)){ packageNames = "com.zaab.duolai"; } return packageNames; } catch (Exception e) { e.printStackTrace(); return "com.zaab.duolai"; } } }
/**
 * 网络类
 */
public class NetWorkUtils {
    public static final boolean isNetWorkAvailable() {
        Context context = MyApplication.getInstance();
        if (context == null) {
            return false;
        }
        ConnectivityManager cm = (ConnectivityManager) MyApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    //判断网络是否正常
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED
                            || info[i].getState() == NetworkInfo.State.CONNECTING) {
                        return true;
                    }
                }
            }
        }
        return false;
    }




    public static String GetNetworkType(Context context)
    {
        String strNetworkType = "";
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            {
                strNetworkType = "WIFI";
            }
            else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                String _strSubTypeName = networkInfo.getSubtypeName();

                Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);

                // TD-SCDMA  networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:  //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            strNetworkType = "3G";
                        }
                        else
                        {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }

                Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
            }
        }

        Log.e("cocos2d-x", "Network Type : " + strNetworkType);

        return strNetworkType;
    }
}

 

/**
 * Created by lk
 * 屏幕管理类
 */
public class WindowUtil {

    private WindowUtil(){
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static WindowManager getWindowManager(Context context){
        return (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    }

    private static DisplayMetrics getMetrics(Context context){
        WindowManager wm = getWindowManager(context);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics;
    }

    /** 获取屏幕的宽度 */
    public static int getWindowsWidth(Context context) {
        return getMetrics(context).widthPixels;
    }

    /** 获取屏幕的高度 */
    public static int getWindowsHeight(Context context) {
        return getMetrics(context).heightPixels;
    }

    /**
     * dp to px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px to dp
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 设置添加屏幕的背景透明度( 0.0f --- 1.0f )
     */
    public static void backgroundAlpha(Activity activity, float bgAlpha) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0f-1.0f
        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        window.setAttributes(lp);

    }

    /**
     * 获得当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    public static int getScreenMode(Activity activity) {
        int screenMode = 0;
        try {
            screenMode = Settings.System.getInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Exception localException) {

        }
        return screenMode;
    }

    /**
     * 设置当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    public static void setScreenMode(Activity activity, int paramInt) {
        try {
            Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 获得当前屏幕亮度值 0--255
     */
    public static int getScreenBrightness(Activity activity) {
        int screenBrightness = 255;
        try {
            screenBrightness = Settings.System.getInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception localException) {

        }
        return screenBrightness;
    }

    /**
     * 设置当前屏幕亮度值 0--255
     */
    public static void saveScreenBrightness(Context context, int paramInt) {
        try {
            Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 保存当前的屏幕亮度值,并使之生效
     */
    public static void setScreenBrightness(Activity activity, int paramInt) {
        Window localWindow = activity.getWindow();
        WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
        float f = paramInt / 255.0F;
        localLayoutParams.screenBrightness = f;
        localWindow.setAttributes(localLayoutParams);
    }

}

以上代码为3个工具类

点击下载

你可能感兴趣的:(IMEI,IMSI,MAC,android授信,网络类型,android基础篇)