91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android常用方法總結

發布時間:2020-07-22 08:39:13 來源:網絡 閱讀:296 作者:huangmeicai 欄目:移動開發

public class Toolkit {

    /**
     *
     * Role:Telecom service providers獲取手機服務商信息 <BR>
     *
     * 需要加入權限<uses-permission
     * android:name="android.permission.READ_PHONE_STATE"/> <BR>
     * Date:2012-3-12 <BR>
     *
     * @author CODYY)allen
     */
    public static String getProvidersName(Context context) {
        String ProvidersName = "nosim";
        try {
            // 返回唯一的用戶ID;就是這張卡的編號神馬的
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String IMSI = telephonyManager.getSubscriberId();
            // IMSI號前面3位460是國家,緊接著后面2位00 02是中國移動,01是中國聯通,03是中國電信。
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002"))
                ProvidersName = "中國移動";
            else if (IMSI.startsWith("46001"))
                ProvidersName = "中國聯通";
            else if (IMSI.startsWith("46003"))
                ProvidersName = "中國電信";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ProvidersName;
        }
        return ProvidersName;
    }

    /**
     * 獲取手機號
     *
     * @param context
     * @return
     */
    public static String getPhone(Context context) {
        TelephonyManager phoneMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return phoneMgr.getLine1Number();
    }

    /**
     * 獲取手機型號
     *
     * @return
     */
    public static String getPhoneType() {
        return Build.MODEL;
    }

    /**
     * 獲取sdk版本
     *
     * @return
     */
    public static String getSDKVersion() {
        return Build.VERSION.SDK;
    }

    /**
     * 獲取版本號
     *
     * @return
     */
    public static String getVersion() {
        return Build.VERSION.RELEASE;
    }

    public static class TelephonyManagerInfo {
        /**
         * 電話狀態: 1.tm.CALL_STATE_IDLE=0 無活動
         *
         * 2.tm.CALL_STATE_RINGING=1 響鈴
         *
         * 3.tm.CALL_STATE_OFFHOOK=2 摘機
         */
        public static int CallState;
        /**
         *
         * 電話方位:(需要權限:android.permission.ACCESS_COARSE_LOCATION)
         */
        public static String CellLocation;

        /**
         *
         * 唯一的設備ID:
         *
         * GSM手機的 IMEI 和 CDMA手機的 MEID.
         *
         * Return null if device ID is not available.
         */
        public static String DeviceId;

        /**
         *
         * 設備的軟件版本號:
         *
         * 例如:the IMEI/SV(software version) for GSM phones.
         *
         * Return null if the software version is not available.
         */
        public static String DeviceSoftwareVersion;

        /**
         *
         * 手機號:
         *
         * GSM手機的 MSISDN.
         *
         * Return null if it is unavailable.
         */
        public static String Line1Number;

        /**
         *
         * 附近的電話的信息:
         *
         * 類型:List<NeighboringCellInfo>
         *
         * 需要權限:android.Manifest.permission#ACCESS_COARSE_UPDATES
         */
        public static List<NeighboringCellInfo> NeighboringCellInfo;// List<NeighboringCellInfo>

        /**
         *
         * 獲取ISO標準的國家碼,即國際長途區號。
         *
         * 注意:僅當用戶已在網絡注冊后有效。
         *
         * 在CDMA網絡中結果也許不可靠。
         */
        public static String NetworkCountryIso;

        /**
         *
         * MCC+MNC(mobile country code + mobile network code)
         *
         * 注意:僅當用戶已在網絡注冊時有效。
         *
         * 在CDMA網絡中結果也許不可靠。
         */
        public static String NetworkOperator;

        /**
         *
         * 按照字母次序的current registered operator(當前已注冊的用戶)的名字
         *
         * 注意:僅當用戶已在網絡注冊時有效。
         *
         * 在CDMA網絡中結果也許不可靠。
         */

        public static String NetworkOperatorName;// String

        /**
         * 當前使用的網絡類型:
         *
         * 例如: NETWORK_TYPE_UNKNOWN 網絡類型未知 0 NETWORK_TYPE_GPRS GPRS網絡 1
         *
         * NETWORK_TYPE_EDGE EDGE網絡 2
         *
         * NETWORK_TYPE_UMTS UMTS網絡 3
         *
         * NETWORK_TYPE_HSDPA HSDPA網絡 8
         *
         * NETWORK_TYPE_HSUPA HSUPA網絡 9
         *
         * NETWORK_TYPE_HSPA HSPA網絡 10
         *
         * NETWORK_TYPE_CDMA CDMA網絡,IS95A 或 IS95B. 4
         *
         * NETWORK_TYPE_EVDO_0 EVDO網絡, revision 0. 5
         *
         * NETWORK_TYPE_EVDO_A EVDO網絡, revision A. 6
         *
         * NETWORK_TYPE_1xRTT 1xRTT網絡 7
         */
        public static int NetworkType;// int

        /**
         *
         * 手機類型:
         *
         * 例如: PHONE_TYPE_NONE 無信號
         *
         * PHONE_TYPE_GSM GSM信號
         *
         * PHONE_TYPE_CDMA CDMA信號
         */

        public static int PhoneType;// int

        /**
         *
         * Returns the ISO country code equivalent for the SIM provider's
         * country code.
         *
         * 獲取ISO國家碼,相當于提供SIM卡的國家碼。
         */
        public static String SimCountryIso;// String

        /**
         *
         * Returns the MCC+MNC (mobile country code + mobile network code) of
         * the provider of the SIM. 5 or 6 decimal digits.
         *
         * 獲取SIM卡提供的移動國家碼和移動網絡碼.5或6位的十進制數字.
         *
         * SIM卡的狀態必須是 SIM_STATE_READY(使用getSimState()判斷).
         */
        public static String SimOperator;// String

        /**
         *
         * 服務商名稱:
         *
         * 例如:中國移動、聯通
         *
         * SIM卡的狀態必須是 SIM_STATE_READY(使用getSimState()判斷).
         */
        public static String SimOperatorName;// String

        /**
         *
         * SIM卡的序列號:
         *
         * 需要權限:READ_PHONE_STATE
         */
        public static String SimSerialNumber;// String

        /**
         *
         * SIM的狀態信息:
         *
         * SIM_STATE_UNKNOWN 未知狀態 0
         *
         * SIM_STATE_ABSENT 沒插卡 1
         *
         * SIM_STATE_PIN_REQUIRED 鎖定狀態,需要用戶的PIN碼解鎖 2
         *
         * SIM_STATE_PUK_REQUIRED 鎖定狀態,需要用戶的PUK碼解鎖 3
         *
         * SIM_STATE_NETWORK_LOCKED 鎖定狀態,需要網絡的PIN碼解鎖 4
         *
         * SIM_STATE_READY 就緒狀態 5
         */
        public static int SimState;// int

        /**
         *
         * 唯一的用戶ID:
         *
         * 例如:IMSI(國際移動用戶識別碼) for a GSM phone.
         *
         * 需要權限:READ_PHONE_STATE
         */
        public static String SubscriberId;// String

        /**
         *
         * 取得和語音郵件相關的標簽,即為識別符
         *
         * 需要權限:READ_PHONE_STATE
         */
        public static String VoiceMailAlphaTag;// String

        /**
         *
         * 獲取語音郵件號碼:
         *
         * 需要權限:READ_PHONE_STATE
         */
        public static String VoiceMailNumber;// String

        /**
         *
         * ICC卡是否存在
         */
        public static boolean hasIccCard;// boolean

        /**
         *
         * 是否漫游:
         *
         * (在GSM用途下)
         */
        public static boolean isNetworkRoaming;
    }

    /**
     * 獲取手機唯一ID
     *
     * @param context
     * @return
     */
    public static String getPhoneUniqueId(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 獲取手機信息實體
     *
     * @param context
     * @return
     */
    public static TelephonyManagerInfo getTelephonyInfo(Context context) {
        TelephonyManagerInfo info = new TelephonyManagerInfo();
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(context.TELEPHONY_SERVICE);
        info.CallState = tm.getCallState();
        info.CellLocation = tm.getCellLocation().toString();
        info.DeviceId = tm.getDeviceId();
        info.DeviceSoftwareVersion = tm.getDeviceSoftwareVersion();
        info.hasIccCard = tm.hasIccCard();
        info.isNetworkRoaming = tm.isNetworkRoaming();
        info.Line1Number = tm.getLine1Number();
        info.NeighboringCellInfo = tm.getNeighboringCellInfo();
        info.NetworkCountryIso = tm.getNetworkCountryIso();
        info.NetworkOperator = tm.getNetworkOperator();
        info.NetworkOperatorName = tm.getNetworkOperatorName();
        info.NetworkType = tm.getNetworkType();
        info.PhoneType = tm.getPhoneType();
        info.SimCountryIso = tm.getSimCountryIso();
        info.SimOperator = tm.getSimOperator();
        info.SimOperatorName = tm.getSimOperatorName();
        info.SimSerialNumber = tm.getSimSerialNumber();
        info.SimState = tm.getSimState();
        info.SubscriberId = tm.getSubscriberId();
        info.VoiceMailAlphaTag = tm.getVoiceMailAlphaTag();
        info.VoiceMailNumber = tm.getVoiceMailNumber();
        return info;
    }

    /**
     * 取得屏幕分辨率大小
     *
     * @param context
     *            Activity上下文
     * @return第一個值為寬度
     */
    public static int[] getDisplayPixes(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new int[] { dm.widthPixels, dm.heightPixels };
    }

    /**
     * 取得屏幕分辨寬度和高度
     *
     * @param context
     *            Activity上下文
     * @return第一個值為寬度
     */
    public static int[] getDisplayWidthHeight(Activity context) {
        Display dis = context.getWindowManager().getDefaultDisplay();
        return new int[] { dis.getWidth(), dis.getHeight() };
    }

    /**
     * 檢查是否有可用的網絡
     *
     * @param context
     *            上下文
     * @return true:有網絡
     */
    public static boolean isAvaliable(Context context) {
        if (isWiFiActive(context) || isNetworkAvailable(context))
            // Toast.makeText(context, "有網絡!", 300).show();
            return true;
        else
            // Toast.makeText(context, "網絡不正常!", 300).show();
            return false;
    }

    /** 返回當前網速 */
    public static long getNetworkSpeed() {
        // TODO Auto-generated method stub
        ProcessBuilder cmd;
        long readBytes = 0;
        BufferedReader rd = null;
        try {
            String[] args = { "/system/bin/cat", "/proc/net/dev" };
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            rd = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line;
            int linecount = 0;
            while ((line = rd.readLine()) != null) {
                linecount++;
                if (line.contains("wlan0") || line.contains("eth0")) {
                    // L.E("獲取流量整條字符串",line);
                    String[] delim = line.split(":");
                    if (delim.length >= 2) {
                        String[] numbers = delim[1].trim().split(" ");// 提取數據
                        readBytes = Long.parseLong(numbers[0].trim());//
                        break;
                    }
                }
            }
            rd.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (rd != null) {
                try {
                    rd.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return readBytes;
    }

    /**
     * 檢查wifi是否可用
     *
     * @param inContext
     * @return
     */
    public static boolean isWiFiActive(Context inContext) {
        WifiManager mWifiManager = (WifiManager) inContext
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
        if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
            System.out.println("**** WIFI is on");
            return true;
        } else {
            System.out.println("**** WIFI is off");
            return false;
        }
    }

    /**
     * 檢查手機網絡(非wifi)是否有用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info == null) {
                return false;
            } else {
                if (info.isAvailable()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判斷是否為wifi的連接ip
     *
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        int ipAddress = getWifiIpInfo(context);
        if (ipAddress > 0)
            return true;
        else
            return false;
    }

    private static int getWifiIpInfo(Context context) {
        // 獲取wifi服務
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 判斷wifi是否開啟
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        // return String.valueOf(wifiInfo.getIpAddress());
        int ipAddress = wifiInfo.getIpAddress();
        return ipAddress;
    }

    /**
     * 獲取wifi ip
     *
     * @return
     */
    public static String getWifiAddress(Context context) {
        int ipAddress = getWifiIpInfo(context);
        return intToIp(ipAddress);
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
    }

    /**
     * 獲取手機mac地址<br/>
     * 錯誤返回12個0
     */
    public static String getMacAddress(Context context) {
        // 獲取mac地址:
        String macAddress = "000000000000";
        try {
            WifiManager wifiMgr = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr
                    .getConnectionInfo());
            if (null != info) {
                if (!TextUtils.isEmpty(info.getMacAddress()))
                    macAddress = info.getMacAddress().replace(":", "");
                else
                    return macAddress;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return macAddress;
        }
        return macAddress;
    }

    /**
     * 獲取手機ip(此方法在android中使用獲取3G網絡ip地址)
     *
     * @return
     * @throws SocketException
     * @throws UnknownHostException
     */
    public static String getLocalIpAddress() throws SocketException {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                    .hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return null;
    }

    /**
     * 獲取本機ip(此方法僅在java程序中)
     *
     * @return
     * @throws UnknownHostException
     */
    public static String getHostAddress() throws UnknownHostException {
        InetAddress address = null;
        address = InetAddress.getLocalHost();
        return address.getHostAddress();
    }

    /**
     * 讀取文本,一次讀取多個字節,默認為1024
     *
     * @param file
     *            文件名稱(在sd卡下面的data/data/應用程序包下面)
     * @param context
     *            上下文
     * @param encode
     *            編碼方式
     * @return
     * @throws IOException
     */
    public static String readFromFileByChar(String file, Context context,
            String encode) throws IOException {
        FileInputStream fis = context.openFileInput(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis,
                encode));
        // Log.i(TAG, br.readLine());
        int index = 0;
        char[] buffer = new char[1024];// 一次性讀取1024個字符
        StringBuffer sb = new StringBuffer();
        while ((index = br.read(buffer)) != -1) {// 一次讀多個字符
            // 同樣屏蔽掉r不顯示
            if ((index == buffer.length) && (buffer[buffer.length - 1] != 'r')) {
                sb.append(buffer);
            } else {
                for (int i = 0; i < index; i++) {
                    if (buffer[i] == 'r') {
                        continue;// 停止執行當前的迭代,然后退回循環開始處
                    } else {
                        sb.append(buffer[i]);
                    }
                }
            }
        }
        br.close();
        fis.close();
        return sb.toString();
        // return br.readLine();
    }

    /**
     * 按行讀取文本
     *
     * @param file
     *            文件名
     * @param context
     *            上下文
     * @param encode
     *            編碼方式
     * @return
     * @throws IOException
     */
    public static String readFromFileByLine(String file, Context context,
            String encode) throws IOException {
        FileInputStream fis = context.openFileInput(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis,
                encode));
        // Log.i(TAG, br.readLine());
        StringBuffer sb = new StringBuffer();
        String temp;
        while ((temp = br.readLine()) != null) {// 一次讀一行
            sb.append(temp);
        }
        br.close();
        fis.close();
        return sb.toString();
        // return br.readLine();
    }

    /**
     * 一次將string內容寫入到文件
     *
     * @param context
     *            上下文
     * @param file
     *            文件名
     * @param content
     *            寫入的內容
     * @throws IOException
     */
    public static void writeToFile(Context context, String file, String content)
            throws IOException {
        FileOutputStream fos = context.openFileOutput(file,
                context.MODE_PRIVATE);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        bw.write(content);
        bw.flush();
        bw.close();
        fos.close();
    }

    /**
     * 將object序列化到filename文件中
     *
     * @param fileName
     *            文件名,包括路徑
     * @param object
     *            序列化的對象
     */
    public static boolean writeFileByObject(String fileName, Object object) {
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.flush();
            oos.close();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 反序列化
     *
     * @param fileName
     *            文件名,包括詳細路徑
     * @return Object類型的對象
     */
    public static Object readFileByObject(String fileName) {
        try {
            FileInputStream fis = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object o = ois.readObject();
            ois.close();
            fis.close();
            return o;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 按照指定的寬度和高度壓縮圖片(這是android 2.2以上才有的方法)
     *
     * @param bm
     * @param w
     * @param h
     * @return
     */
    public static Bitmap compressBitmap(Bitmap bm, int w, int h) {
        return ThumbnailUtils.extractThumbnail(bm, w, h);
    }

    /**
     * 等比例壓縮圖片
     *
     * @param is
     *            圖片輸入流
     * @param scalePix
     *            壓縮的尺寸
     * @return
     */
    public static Bitmap compressBitmapByscale(InputStream is, int scalePix) {
        BitmapFactory.Options opt = new Options();
        opt.inSampleSize = scalePix;
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 等比例壓縮圖片
     *
     * @param data
     *            byte[]數組
     *
     * @param ratio
     *            壓縮的尺寸
     * @return
     */
    public static Bitmap compressBitmap(byte[] data, int ratio) {
        BitmapFactory.Options opts = new Options();
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = ratio;
        // 得到新的圖片
        return BitmapFactory.decodeByteArray(data, 0, data.length, opts);

    }

    /**
     * 自動壓縮圖片(根據能夠壓縮的比例)
     *
     * @param map
     * @return
     */
    public static Bitmap compressBitmapAuto(Bitmap map, int scalePix) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] data = os.toByteArray();
        opts.inJustDecodeBounds = true;
        map.compress(CompressFormat.PNG, 100, os);
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        opts.inJustDecodeBounds = false;
        int be = (int) (opts.outHeight / (float) scalePix);
        if (be <= 0)
            be = 1;
        opts.inSampleSize = be;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
        return bitmap;
    }

    /** 根據屏幕大小適屏壓縮 --2012/11/13-- */
    public static Bitmap compressBitmapFixDisplay(Activity context, byte[] data) {
        BitmapFactory.Options opts = new Options();
        opts.inJustDecodeBounds = true;// 設置查看圖片的大小,不分配內存
        BitmapFactory.decodeByteArray(data, 0, data.length, opts);
        int height = context.getWindowManager().getDefaultDisplay().getHeight();// 獲取屏幕大小
        int width = context.getWindowManager().getDefaultDisplay().getWidth();
        int hratio = (int) Math.ceil(opts.outHeight / (float) height);// 圖片的高度比上屏幕的高度
        int wratio = (int) Math.ceil(opts.outWidth / (float) width);
        if (hratio > 1 || wratio > 1) {// 如果圖片超出屏幕范圍
            if (hratio > wratio)// 如果高度大于寬度
                opts.inSampleSize = hratio;
            else
                opts.inSampleSize = wratio;
        }
        opts.inJustDecodeBounds = false;// 設置分配圖片的大小
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                opts);
        return bitmap;
    }

    /**
     * 壓縮圖片
     *
     * @param bm
     *            所要轉換的bitmap
     * @param newWidth新的寬
     * @param newHeight新的高
     * @return 指定寬高的bitmap
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 獲得圖片的寬高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 計算縮放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要縮放的matrix參數
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的圖片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        if (!bm.isRecycled())// 回收bitmap
            bm.recycle();
        return newbm;
    }

    /**
     * 動態設置ImageView的布局寬度和高度
     *
     * @param iv
     *            ImageView對象
     * @param width
     *            要設置的寬度(0:充滿父容器)
     * @param height
     *            要設置的高度(0:充滿父容器)
     */
    public static void setImagePixes(ImageView iv, int width, int height) {
        ViewGroup.LayoutParams params = iv.getLayoutParams();
        if (width == 0 && height != 0)// 如果寬度為0
        {
            params.height = height;
            params.width = ViewGroup.LayoutParams.FILL_PARENT;
        } else if (height == 0 && width != 0) {// 高度為 0
            params.height = ViewGroup.LayoutParams.FILL_PARENT;
            params.width = width;
        } else if (width == 0 && height == 0) {
            params.height = ViewGroup.LayoutParams.FILL_PARENT;
            params.width = ViewGroup.LayoutParams.FILL_PARENT;
        } else {
            params.height = height;
            params.width = width;
        }
        iv.setLayoutParams(params);
    }

    /** activity轉換為view */
    @SuppressWarnings("deprecation")
    public static View activityToView(Context parent, Intent intent) {
        LocalActivityManager mLocalActivityManager = new LocalActivityManager(
                (Activity) parent, true);
        final Window w = mLocalActivityManager.startActivity("TagName", intent);
        final View wd = w != null ? w.getDecorView() : null;
        if (wd != null) {
            wd.setVisibility(View.VISIBLE);
            wd.setFocusableInTouchMode(true);
            ((ViewGroup) wd)
                    .setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        }
        return wd;
    }

    /***
     * 動態設置listview的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // params.height += 5;// if without this statement,the listview will be
        // a
        // little short
        // listView.getDividerHeight()獲取子項間分隔符占用的高度
        // params.height最后得到整個ListView完整顯示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 將Drawable轉化為Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
                .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 將圖片的四角圓化
     *
     * @param bitmap
     * @param radius
     *            圓角弧度,數值越大弧度越大
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int radius) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        // 得到畫布
        Canvas canvas = new Canvas(output);

        // 將畫布的四角圓化
        final int color = Color.RED;
        final Paint paint = new Paint();
        // 得到與圖像相同大小的區域 由構造的四個值決定區域的位置以及大小
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        // 值越大角度越明顯
        final float roundPx = radius;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        // drawRoundRect的第2,3個參數一樣則畫的是正圓的一角,如果數值不同則是橢圓的一角
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // 設置形式為背景
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 獲得帶倒影的圖片方法
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
        final int reflectionGap = 4;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
                width, height / 2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                (height + height / 2), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
                bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
                0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);// 設置陰影
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                + reflectionGap, paint);
        return bitmapWithReflection;
    }

    /**
     * 向preferences寫入數據
     *
     * @param context
     *            上下文
     * @param key
     *            鍵
     * @param value
     *            寫入的內容
     */
    public static void writeToPreferences(Context context, String filename,
            String key, String value) {
        // 得到preferences對象
        SharedPreferences.Editor editor = context.getSharedPreferences(
                filename, android.content.Context.MODE_PRIVATE).edit();
        // editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * 向preference中讀取數據 data/data/package/shared_prefs
     *
     * @param context
     *            上下文
     * @param filename
     *            文件名
     * @param key
     *            鍵
     * @param defaultValue
     *            默認值
     * @return
     */
    public static String readFromPreferences(Context context, String filename,
            String key, String defaultValue) {
        // 得到preferences對象
        SharedPreferences preferences = context.getSharedPreferences(filename,
                android.content.Context.MODE_PRIVATE
                        | android.content.Context.MODE_APPEND);
        return preferences.getString(key, defaultValue);
    }

    /**
     * 加載properties文件
     *
     * @param context
     * @param file
     * @return
     * @throws Exception
     */
    public static Properties loadProperties(Context context, String file,
            String encode) throws Exception {
        Properties properties = new Properties();
        FileInputStream s = new FileInputStream(file);
        properties.load(s);
        return properties;
    }

    /**
     * 保存到properties文件中
     *
     * @param context
     * @param file
     * @param properties
     * @throws Exception
     */
    public static void saveProperties(Context context, String file,
            String encode, Properties properties) throws Exception {
        FileOutputStream s = new FileOutputStream(file, false);
        properties.store(s, "");
    }

    // ---------------------------------------------------------------------------------------------------

    /**
     * 從網絡上下載
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static Bitmap getBitMapFromUrl(String url) throws IOException {
        Bitmap bitmap = null;
        URL u = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        u = new URL(url);
        conn = (HttpURLConnection) u.openConnection();
        is = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(is);
        return bitmap;
    }

    /**
     * 異步加載網絡圖片
     *
     * @param src圖片路徑
     * @param iv
     *            p_w_picpathview
     * @param callback回調接口
     */
    public static void loadImage(final String src, final ImageView iv,
            final ImageCallBack callback) {
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callback.setImageBitmap((Bitmap) msg.obj, iv, src);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = getBitMapFromUrl(src);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    Message msg = handler.obtainMessage(0, bitmap);
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    /**
     * 獲取網絡byte流的圖片
     *
     * @param src
     * @return
     * @throws Exception
     */
    public static byte[] getImageBytes(String src) throws Exception {
        URL url = new URL(src);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);// 設置延遲時間為5s
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        return bos.toByteArray();
    }

    /**
     * 壓縮圖片
     *
     * @param bm
     *            所要轉換的bitmap
     * @param newWidth新的寬
     * @param newHeight新的高
     * @return 指定寬高的bitmap
     */
    public static Bitmap zoomBitmap(byte[] data, int newWidth, int newHeight) {
        BitmapFactory.Options opts = new Options();
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = 10;
        // 得到新的圖片
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                opts);
        // 獲得圖片的寬高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 計算縮放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要縮放的matrix參數
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
                true);
        if (!bitmap.isRecycled())// 回收bitmap
            bitmap.recycle();
        return newbm;
    }

    /**
     * 異步加載網絡圖片
     *
     * @param src
     *            url地址
     * @param iv
     *            傳入的iamgeView
     * @param callback
     *            回調函數
     */
    public static void AsycloadImage(final String src, final ImageView iv,
            final ImageCallBack callback) {
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callback.setImageBitmap((Bitmap) msg.obj, iv, src);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] data = null;
                Bitmap bitmap = null;
                try {
                    data = getImageBytes(src);
                    bitmap = compressBitmap(data, 3);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    Message msg = handler.obtainMessage(0, bitmap);
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    /**
     * 異步加載圖片
     *
     * @param url
     *            圖片路徑
     * @param iv
     *            ImageView
     * @param imgCache
     *            緩存
     * @param callback
     *            回調接口
     */
    public static void AyncLoadImageFromUrl(final String url,
            final ImageView iv,
            final Map<String, SoftReference<Bitmap>> imgCache,
            final ImageCallBack callback) {
        if (imgCache.containsKey(url))// 如果緩存中存在
        {
            iv.setImageBitmap(imgCache.get(url).get());
            return;
        }
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callback.setImageBitmap((Bitmap) msg.obj, iv, url);
            }
        };
        new Thread(new Runnable() {

            @Override
            public void run() {
                byte[] data = null;
                Bitmap bitmap = null;
                try {
                    data = getImageBytes(url);
                    bitmap = compressBitmap(data, 3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    // 保存到緩存中
                    // 將圖片保存到緩存中
                    imgCache.put(url, new SoftReference<Bitmap>(bitmap));
                    Message msg = handler.obtainMessage(0, bitmap);
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    /**
     * 保存圖片到sdcard,并且返回圖片名稱,帶后綴名
     *
     * @param context
     * @param fileName
     *            圖片目錄名稱
     * @param photo
     *            圖片路徑
     * @throws IOException
     */
    public static String saveImgToSdcard(Context context, String fileName,
            String photo) throws IOException {
        String url = photo;
        // 獲取圖片名稱,包含后綴
        String imgName = url.substring(url.lastIndexOf("/") + 1, url.length());
        URL Url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
        InputStream is = conn.getInputStream();
        String saveUrl = context.getFilesDir() + "/" + fileName + "/" + imgName;
        File file = new File(saveUrl);
        // 如果圖片文件存在
        if (file.exists())
            return imgName;
        FileOutputStream fos = new FileOutputStream(file);
        byte[] data = new byte[512];
        int len = 0;
        while ((len = is.read(data)) != -1) {
            fos.write(data, 0, len);
        }
        fos.flush();
        fos.close();
        return imgName;
    }

    /**
     * 保存圖片到指定的目錄
     *
     * @param context
     *            上下文
     * @param filedir
     *            圖片目錄名稱
     * @param name
     *            圖片名稱
     * @param bitmap
     *            圖片
     * @throws Exception
     */
    public static void saveBitmapToSdcard(Context context, String filedir,
            String name, Bitmap bitmap) throws Exception {
        String path = context.getFilesDir() + File.separator + filedir
                + File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(path + name + ".png");
        if (file.exists())
            return;
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fos);
        fos.close();
    }

    /** 從sdcard制定目錄讀取圖片 */
    public static Bitmap getBitmapFromSdcard(Context context, String file,
            String name) {
        String src = context.getFilesDir() + "/" + file + "/" + name;
        Bitmap bitmap = BitmapFactory.decodeFile(src);
        return bitmap;
    }

    /**
     * 從緩存中讀取
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static Bitmap getImgFromCache(final String url, final ImageView iv,
            final Map<String, SoftReference<Bitmap>> imgCache,
            final ImageCallBack callback) throws Exception {
        // 從內存中讀取
        if (imgCache.containsKey(url)) {
            synchronized (imgCache) {
                SoftReference<Bitmap> bitmapReference = imgCache.get(url);
                if (null != bitmapReference) {
                    return bitmapReference.get();
                }
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callback.setImageBitmap((Bitmap) msg.obj, iv, url);
            }
        };
        // 從網絡中下載
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = getBitMapFromUrl(url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 將圖片保存進內存中
                imgCache.put(url, new SoftReference<Bitmap>(bitmap));
                Message msg = handler.obtainMessage(0, bitmap);
                handler.sendMessage(msg);
            }
        }).start();
        return null;
    }

    public interface ImageCallBack {
        public void setImageBitmap(Bitmap bitmap, ImageView iv, String url);
    }

    /**
     * get 請求
     *
     * @param url路徑
     * @return
     * @throws Exception
     * @throws ClientProtocolException
     */
    public static HttpResponse get(String url) throws Exception {
        HttpResponse response = null;
        HttpClient client = new DefaultHttpClient();
        // 設置連接超時
        client.getParams().setIntParameter(
                HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
        // 設置編碼
        // client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
        // "gb2312");
        // get方式
        HttpGet httpRequest = new HttpGet(url);
        // 發出一個request,并返回一個基于http協議的response
        // System.out.println("------toolkit 1066----------");
        response = client.execute(httpRequest);
        return response;
    }

    /**
     * post請求
     *
     * @param path
     *            請求的地址
     * @param params
     *            參數列表
     * @return
     * @throws Exception
     */
    public static InputStream postRequest(String path,
            Map<String, String> params) throws Exception {
        // 封裝請求參數
        List<NameValuePair> pair = new ArrayList<NameValuePair>();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                pair.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }
        // 把請求參數變成請求體部分
        UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");       
       
       
        // 使用HttpPost對象設置發送的URL路徑
        final HttpPost post = new HttpPost(path);
        // 發送請求體
        post.setEntity(uee);
        // 創建一個瀏覽器對象,以把POST對象向服務器發送,并返回響應消息
        DefaultHttpClient dhc = new DefaultHttpClient();
        // 設置連接超時
        dhc.getParams().setIntParameter(
                HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
        dhc.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000); // 設置等待數據超時10s
        HttpResponse response = dhc.execute(post);
        Log.e("TAG", "服務器返回狀態:----" + response.getStatusLine().getStatusCode());
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            return response.getEntity().getContent();
        } else
            post.abort();
        return null;
    }

    /**
     * post請求
     *
     * @param url路徑
     * @param list
     *            參數列表
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static HttpResponse post(String url, List<BasicNameValuePair> list,
            String encode) throws Throwable {
        HttpResponse response = null;
        HttpClient client = new DefaultHttpClient();
        // 設置連接超時
        client.getParams().setIntParameter(
                HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
        client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
                5000); // 設置等待數據超時5s
        // 創建一個 基于http協議的請求(post方式)
        HttpPost httpRequest = new HttpPost(url);
        if (list != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
            // 將請求中的參數信息放置到request中
            httpRequest.setEntity(entity);
        }
        // 發出一個request,并返回一個基于http協議的response
        response = client.execute(httpRequest);
        return response;

    }

    /*
     * 參數說明: uploadUrl: Servlet的url fileName: 上傳圖片的文件名(如: qq.png) fileUrl:
     * 上傳文件在手機客戶端的完整路徑(如: /sdcard/qq.png)
     */
    public static InputStream upload(String uploadUrl, String fileName,
            String fileUrl) throws Exception {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        InputStream is = null;
        URL url = new URL(uploadUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        /* 允許Input、Output,不使用Cache */
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        /* 設置傳送的method=POST */
        conn.setRequestMethod("POST");
        /* setRequestProperty */
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
                + boundary);
        // 將phone放置到請求的頭部

        if (fileName != null && fileUrl != null) {
            conn.setRequestProperty("picName", fileName);
            /* 設置DataOutputStream */
            DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file1\";filename=\"" + fileName + "\"" + end);
            ds.writeBytes(end);

            /* 取得文件的FileInputStream */
            FileInputStream fStream = new FileInputStream(fileUrl);
            /* 設置每次寫入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int length = -1;
            /* 從文件讀取數據至緩沖區 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 將資料寫入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

            /* close streams */
            fStream.close();
            ds.flush();
            ds.close();
        }
        /* 取得Response內容 */
        is = conn.getInputStream();
        return is;
    }

    // -------------------------------------加密,驗證,轉換系列-----------------------------------------------------------
    /**
     * 驗證是否為手機號碼
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        // Pattern p =
        // Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,2,5-9]))\\d{8}$");
        Pattern p = Pattern.compile("^([0-9]{3})\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 驗證輸入是否為郵箱
     *
     * @param strEmail
     * @return
     */
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }

    /**
     * 驗證輸入是否6位數字
     *
     * @param strEmail
     * @return
     */
    public static boolean isCode(String strCode) {
        String strPattern = "^[0-9]{6}";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strCode);
        return m.matches();
    }

    /**
     * 驗證輸入是否6位字符包含數字和字母,不包含特殊字符
     *
     * @param strEmail
     * @return
     */
    public static boolean isCheckCode(String strCode) {
        String strPattern = "^[0-9a-zA-Z]{6}";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strCode);
        return m.matches();
    }

    /**
     * 驗證輸入是否6到12位上字符包含數字和字母,包含特殊字符
     *
     * @param strEmail
     * @return
     */
    public static boolean isPassCode(String strCode) {
        String strPattern = "^[0-9a-zA-Z@*%#()><!_~]{6,12}";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strCode);
        return m.matches();
    }

    /**
     * 過濾url
     *
     * @param str
     * @return
     */
    public static boolean isLegalUrlParameters(String str) {
        String strPattern = "[&=\\s]+";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 驗證ip
     *
     * @param text
     * @return
     */
    public static boolean isIp(String text) {
        if (text != null && text != "") {
            // 定義正則表達式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判斷ip地址是否與正則表達式匹配
            if (text.matches(regex)) {
                // 返回判斷信息
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * md5加密
     *
     * @param s
     * @return
     * @throws Exception
     */
    public final static String MD5(String s) throws Exception {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };

        byte[] strTemp = s.getBytes();
        MessageDigest mdTemp = MessageDigest.getInstance("MD5");
        mdTemp.update(strTemp);
        byte[] md = mdTemp.digest();
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    /**
     * 加密
     *
     * @param ***c
     *            原文
     * @param sKey
     *            密碼是16位
     * @return
     * @throws Exception
     */
    public static String AESEncrypt(String ***c, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key為空null");
            return null;
        }
        // 判斷Key是否為16位
        if (sKey.length() != 16) {
            System.out.print("Key無效");
            return null;
        }
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(***c.getBytes());
        return byte2hex(encrypted).toLowerCase();
    }

    /**
     * 解密
     *
     * @param ***c
     * @param sKey密碼是16位
     * @return
     * @throws Exception
     */
    public static String AESDecrypt(String ***c, String sKey) throws Exception {
        // 判斷Key是否正確
        if (sKey == null) {
            System.out.print("Key為空null");
            return null;
        }
        // 判斷Key是否為16位
        if (sKey.length() != 16) {
            System.out.print("Key無效");
            return null;
        }
        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = hex2byte(***c);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    }

    private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
            (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
            (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
            (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' };

    /**
     * 十六進制無符號整數形式
     *
     * @param raw
     * @param len
     * @return
     */
    public static String getHex(byte[] raw, int len) {
        byte[] hex = new byte[2 * len];
        int index = 0;
        int pos = 0;

        for (byte b : raw) {
            if (pos >= len)
                break;

            pos++;
            int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }
        return new String(hex);
    }

    /**
     * 轉換為10進制無符號字符串
     *
     * @param bytes
     * @return
     */
    public static long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    /**
     * 二進制轉換為16進制
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * 16進制轉換為二進制
     *
     * @param strhex
     * @return
     */
    public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }

    /**
     * 16進制字符轉換為int
     *
     * @param c
     * @return
     */
    public static int reverseToInt(char c) {
        if (c == 'A')
            return 10;
        else if (c == 'B')
            return 11;
        else if (c == 'C')
            return 12;
        else if (c == 'D')
            return 13;
        else if (c == 'E')
            return 14;
        else if (c == 'F')
            return 15;
        else
            return Integer.parseInt(String.valueOf(c));
    }

    /**
     * 16進制加法
     *
     * @param src1
     * @param src2
     * @return
     */
    public static String hexAdd(String src1, String src2) {
        int length2 = src1.toUpperCase().length();
        int length3 = src2.toUpperCase().length();
        String extend = "";
        char sum[] = null;
        if (length2 > length3) {// 如果src1的長度大于src2
            int num = length2 - length3;
            sum = new char[length2];
            String zero = "";
            for (int i = 0; i < num; i++) {
                zero += "0";
            }
            src2 = zero + src2;
            // 遍歷數組,然后相加
            int add = 0, rest = 0;
            for (int i = length2 - 1; i >= 0; i--) {
                int a = reverseToInt(src1.toUpperCase().charAt(i));
                int b = reverseToInt(src2.toUpperCase().charAt(i));
                if (a + b + add >= 16) {
                    int temp = add;
                    add = (a + b + add) / 16;
                    rest = (a + b + temp) % 16;
                    sum[i] = reverseToChar(rest);
                } else {
                    sum[i] = reverseToChar(a + b + add);
                    add = 0;
                }
            }
        } else if (length2 < length3) {// src1的長度小于src2
            int num = length3 - length2;
            sum = new char[length3];
            String zero = "";
            for (int i = 0; i < num; i++) {
                zero += "0";
            }
            src1 = zero + src1;
            // 遍歷數組,然后相加
            int add = 0, rest = 0;
            for (int i = length3 - 1; i >= 0; i--) {
                int a = reverseToInt(src1.toUpperCase().charAt(i));
                int b = reverseToInt(src2.toUpperCase().charAt(i));
                if (a + b + add >= 16) {
                    int temp = add;
                    add = (a + b + add) / 16;
                    rest = (a + b + temp) % 16;
                    sum[i] = reverseToChar(rest);
                } else {
                    sum[i] = reverseToChar(a + b + add);
                    add = 0;
                }
            }
        } else {// 如果相等
            // 遍歷數組,然后相加
            sum = new char[length3];
            int add = 0, rest = 0;
            for (int i = length3 - 1; i >= 0; i--) {
                int a = reverseToInt(src1.toUpperCase().charAt(i));
                int b = reverseToInt(src2.toUpperCase().charAt(i));
                if (a + b + add >= 16) {
                    int temp = add;
                    add = (a + b + add) / 16;
                    rest = (a + b + temp) % 16;
                    sum[i] = reverseToChar(rest);
                    if (i == 0) {// 如果i==0
                        extend = String.valueOf(add);
                    }
                } else {
                    sum[i] = reverseToChar(a + b + add);
                    add = 0;
                }
            }
        }
        return extend + String.valueOf(sum);
    }

    /**
     * ×××轉為16進制表示的char
     *
     * @param num
     * @return
     */
    public static char reverseToChar(int num) {
        /*
         * if (num == 10) return 'A'; else if (num == 11) return 'B'; else if
         * (num == 12) return 'C'; else if (num == 13) return 'D'; else if (num
         * == 14) return 'E'; else if (num == 15) return 'F'; else return
         * String.valueOf(num).charAt(0);
         */
        return Integer.toHexString(num).charAt(0);
    }

    /**
     * 16進制字符按位取反
     *
     * @param num
     * @return
     */
    public static String revers(String num) {
        num = num.toUpperCase();
        char array[] = num.toCharArray();
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 'A')
                array[i] = reverseToChar(15 - 10);
            else if (array[i] == 'B')
                array[i] = reverseToChar(15 - 11);
            else if (array[i] == 'C')
                array[i] = reverseToChar(15 - 12);
            else if (array[i] == 'D')
                array[i] = reverseToChar(15 - 13);
            else if (array[i] == 'E')
                array[i] = reverseToChar(15 - 14);
            else if (array[i] == 'F')
                array[i] = reverseToChar(15 - 15);
            else
                array[i] = reverseToChar(15 - Integer.parseInt(String
                        .valueOf(array[i])));
        }
        //
        return String.valueOf(array);
    }

    /**
     * 輸入流轉換為byte數組
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static byte[] streamToBytes(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];

        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        return os.toByteArray();
    }

    /**
     * 將輸入流轉為字符串
     *
     * @param is
     *            輸入流
     * @param encode
     *            編碼方式
     * @return
     * @throws Exception
     */
    public static String streamToString(InputStream is, String encode)
            throws Exception {

        byte[] data = streamToBytes(is);
        return new String(data, encode);
    }

    /**
     * 將String轉換成InputStream
     *
     * @param in
     * @return
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    public static InputStream StringTOInputStream(String in, String encode)
            throws IOException {
        ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes(encode));
        return is;
    }

    /**
     * 將byte數組轉換為輸入流
     *
     * @param data
     * @return
     */
    public static InputStream ByteToStream(byte[] data) {
        ByteArrayInputStream os = new ByteArrayInputStream(data);
        return os;
    }

    /**
     * 資源文件轉換為bitmap
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap getBitmapFromResource(Context context, int resId) {
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is);
    }

    /**
     * 返回當前日期xxxx年x月xx日x星期
     *
     * @return
     */
    public static String getDate() {
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        int w = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        String mDate = c.get(Calendar.YEAR) + "年" + c.get(Calendar.MONTH) + "月"
                + c.get(Calendar.DATE) + "日  " + weekDays[w];
        return mDate;
    }
}


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

呼伦贝尔市| 黄山市| 诏安县| 偏关县| 东至县| 顺义区| 资讯| 宕昌县| 湾仔区| 息烽县| 安阳市| 卢湾区| 闽侯县| 米林县| 松江区| 廉江市| 南溪县| 广饶县| 青铜峡市| 高密市| 漯河市| 富民县| 方山县| 颍上县| 吴桥县| 九龙城区| 务川| 石渠县| 临沭县| 新沂市| 家居| 东方市| 丽水市| 南涧| 汕头市| 兰考县| 穆棱市| 丹凤县| 托克托县| 祁连县| 绍兴县|