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請求框<br/>
     */
    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<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否還有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一個元素
                Enumeration<InetAddress> 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個工具類

點擊下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章