android 經常使用方法總結

  1. public class Toolkit {  
  2.   
  3.     /** 
  4.      *  
  5.      * Role:Telecom service providers獲取手機服務商信息 <BR> 
  6.      *  
  7.      * 須要加入權限<uses-permission 
  8.      * android:name="android.permission.READ_PHONE_STATE"/> <BR> 
  9.      * Date:2012-3-12 <BR> 
  10.      *  
  11.      * @author CODYY)allen 
  12.      */  
  13.     public static String getProvidersName(Context context) {  
  14.         String ProvidersName = "nosim";  
  15.         try {  
  16.             // 返回惟一的用戶ID;就是這張卡的編號神馬的  
  17.             TelephonyManager telephonyManager = (TelephonyManager) context  
  18.                     .getSystemService(Context.TELEPHONY_SERVICE);  
  19.             String IMSI = telephonyManager.getSubscriberId();  
  20.             // IMSI號前面3位460是國家,緊接着後面2位00 02是中國移動,01是中國聯通,03是中國電信。  
  21.             if (IMSI.startsWith("46000") || IMSI.startsWith("46002"))  
  22.                 ProvidersName = "中國移動";  
  23.             else if (IMSI.startsWith("46001"))  
  24.                 ProvidersName = "中國聯通";  
  25.             else if (IMSI.startsWith("46003"))  
  26.                 ProvidersName = "中國電信";  
  27.         } catch (Exception e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.             return ProvidersName;  
  31.         }  
  32.         return ProvidersName;  
  33.     }  
  34.   
  35.     /** 
  36.      * 獲取手機號 
  37.      *  
  38.      * @param context 
  39.      * @return 
  40.      */  
  41.     public static String getPhone(Context context) {  
  42.         TelephonyManager phoneMgr = (TelephonyManager) context  
  43.                 .getSystemService(Context.TELEPHONY_SERVICE);  
  44.         return phoneMgr.getLine1Number();  
  45.     }  
  46.   
  47.     /** 
  48.      * 獲取手機型號 
  49.      *  
  50.      * @return 
  51.      */  
  52.     public static String getPhoneType() {  
  53.         return Build.MODEL;  
  54.     }  
  55.   
  56.     /** 
  57.      * 獲取sdk版本 
  58.      *  
  59.      * @return 
  60.      */  
  61.     public static String getSDKVersion() {  
  62.         return Build.VERSION.SDK;  
  63.     }  
  64.   
  65.     /** 
  66.      * 獲取版本號 
  67.      *  
  68.      * @return 
  69.      */  
  70.     public static String getVersion() {  
  71.         return Build.VERSION.RELEASE;  
  72.     }  
  73.   
  74.     public static class TelephonyManagerInfo {  
  75.         /** 
  76.          * 電話狀態: 1.tm.CALL_STATE_IDLE=0 無活動 
  77.          *  
  78.          * 2.tm.CALL_STATE_RINGING=1 響鈴 
  79.          *  
  80.          * 3.tm.CALL_STATE_OFFHOOK=2 摘機 
  81.          */  
  82.         public static int CallState;  
  83.         /** 
  84.          *  
  85.          * 電話方位:(須要權限:android.permission.ACCESS_COARSE_LOCATION) 
  86.          */  
  87.         public static String CellLocation;  
  88.   
  89.         /** 
  90.          *  
  91.          * 惟一的設備ID: 
  92.          *  
  93.          * GSM手機的 IMEI 和 CDMA手機的 MEID. 
  94.          *  
  95.          * Return null if device ID is not available. 
  96.          */  
  97.         public static String DeviceId;  
  98.   
  99.         /** 
  100.          *  
  101.          * 設備的軟件版本號: 
  102.          *  
  103.          * 例如:the IMEI/SV(software version) for GSM phones. 
  104.          *  
  105.          * Return null if the software version is not available. 
  106.          */  
  107.         public static String DeviceSoftwareVersion;  
  108.   
  109.         /** 
  110.          *  
  111.          * 手機號: 
  112.          *  
  113.          * GSM手機的 MSISDN. 
  114.          *  
  115.          * Return null if it is unavailable. 
  116.          */  
  117.         public static String Line1Number;  
  118.   
  119.         /** 
  120.          *  
  121.          * 附近的電話的信息: 
  122.          *  
  123.          * 類型:List<NeighboringCellInfo> 
  124.          *  
  125.          * 須要權限:android.Manifest.permission#ACCESS_COARSE_UPDATES 
  126.          */  
  127.         public static List<NeighboringCellInfo> NeighboringCellInfo;// List<NeighboringCellInfo>  
  128.   
  129.         /** 
  130.          *  
  131.          * 獲取ISO標準的國家碼,即國際長途區號。 
  132.          *  
  133.          * 注意:僅當用戶已在網絡註冊後有效。 
  134.          *  
  135.          * 在CDMA網絡中結果也許不可靠。 
  136.          */  
  137.         public static String NetworkCountryIso;  
  138.   
  139.         /** 
  140.          *  
  141.          * MCC+MNC(mobile country code + mobile network code) 
  142.          *  
  143.          * 注意:僅當用戶已在網絡註冊時有效。 
  144.          *  
  145.          * 在CDMA網絡中結果也許不可靠。 
  146.          */  
  147.         public static String NetworkOperator;  
  148.   
  149.         /** 
  150.          *  
  151.          * 按照字母次序的current registered operator(當前已註冊的用戶)的名字 
  152.          *  
  153.          * 注意:僅當用戶已在網絡註冊時有效。 
  154.          *  
  155.          * 在CDMA網絡中結果也許不可靠。 
  156.          */  
  157.   
  158.         public static String NetworkOperatorName;// String  
  159.   
  160.         /** 
  161.          * 當前使用的網絡類型: 
  162.          *  
  163.          * 例如: NETWORK_TYPE_UNKNOWN 網絡類型未知 0 NETWORK_TYPE_GPRS GPRS網絡 1 
  164.          *  
  165.          * NETWORK_TYPE_EDGE EDGE網絡 2 
  166.          *  
  167.          * NETWORK_TYPE_UMTS UMTS網絡 3 
  168.          *  
  169.          * NETWORK_TYPE_HSDPA HSDPA網絡 8 
  170.          *  
  171.          * NETWORK_TYPE_HSUPA HSUPA網絡 9 
  172.          *  
  173.          * NETWORK_TYPE_HSPA HSPA網絡 10 
  174.          *  
  175.          * NETWORK_TYPE_CDMA CDMA網絡,IS95A 或 IS95B. 4 
  176.          *  
  177.          * NETWORK_TYPE_EVDO_0 EVDO網絡, revision 0. 5 
  178.          *  
  179.          * NETWORK_TYPE_EVDO_A EVDO網絡, revision A. 6 
  180.          *  
  181.          * NETWORK_TYPE_1xRTT 1xRTT網絡 7 
  182.          */  
  183.         public static int NetworkType;// int  
  184.   
  185.         /** 
  186.          *  
  187.          * 手機類型: 
  188.          *  
  189.          * 例如: PHONE_TYPE_NONE 無信號 
  190.          *  
  191.          * PHONE_TYPE_GSM GSM信號 
  192.          *  
  193.          * PHONE_TYPE_CDMA CDMA信號 
  194.          */  
  195.   
  196.         public static int PhoneType;// int  
  197.   
  198.         /** 
  199.          *  
  200.          * Returns the ISO country code equivalent for the SIM provider's 
  201.          * country code. 
  202.          *  
  203.          * 獲取ISO國家碼,至關於提供SIM卡的國家碼。 
  204.          */  
  205.         public static String SimCountryIso;// String  
  206.   
  207.         /** 
  208.          *  
  209.          * Returns the MCC+MNC (mobile country code + mobile network code) of 
  210.          * the provider of the SIM. 5 or 6 decimal digits. 
  211.          *  
  212.          * 獲取SIM卡提供的移動國家碼和移動網絡碼.5或6位的十進制數字. 
  213.          *  
  214.          * SIM卡的狀態必須是 SIM_STATE_READY(使用getSimState()判斷). 
  215.          */  
  216.         public static String SimOperator;// String  
  217.   
  218.         /** 
  219.          *  
  220.          * 服務商名稱: 
  221.          *  
  222.          * 例如:中國移動、聯通 
  223.          *  
  224.          * SIM卡的狀態必須是 SIM_STATE_READY(使用getSimState()判斷). 
  225.          */  
  226.         public static String SimOperatorName;// String  
  227.   
  228.         /** 
  229.          *  
  230.          * SIM卡的序列號: 
  231.          *  
  232.          * 須要權限:READ_PHONE_STATE 
  233.          */  
  234.         public static String SimSerialNumber;// String  
  235.   
  236.         /** 
  237.          *  
  238.          * SIM的狀態信息: 
  239.          *  
  240.          * SIM_STATE_UNKNOWN 未知狀態 0 
  241.          *  
  242.          * SIM_STATE_ABSENT 沒插卡 1 
  243.          *  
  244.          * SIM_STATE_PIN_REQUIRED 鎖定狀態,須要用戶的PIN碼解鎖 2 
  245.          *  
  246.          * SIM_STATE_PUK_REQUIRED 鎖定狀態,須要用戶的PUK碼解鎖 3 
  247.          *  
  248.          * SIM_STATE_NETWORK_LOCKED 鎖定狀態,須要網絡的PIN碼解鎖 4 
  249.          *  
  250.          * SIM_STATE_READY 就緒狀態 5 
  251.          */  
  252.         public static int SimState;// int  
  253.   
  254.         /** 
  255.          *  
  256.          * 惟一的用戶ID: 
  257.          *  
  258.          * 例如:IMSI(國際移動用戶識別碼) for a GSM phone. 
  259.          *  
  260.          * 須要權限:READ_PHONE_STATE 
  261.          */  
  262.         public static String SubscriberId;// String  
  263.   
  264.         /** 
  265.          *  
  266.          * 取得和語音郵件相關的標籤,即爲識別符 
  267.          *  
  268.          * 須要權限:READ_PHONE_STATE 
  269.          */  
  270.         public static String VoiceMailAlphaTag;// String  
  271.   
  272.         /** 
  273.          *  
  274.          * 獲取語音郵件號碼: 
  275.          *  
  276.          * 須要權限:READ_PHONE_STATE 
  277.          */  
  278.         public static String VoiceMailNumber;// String  
  279.   
  280.         /** 
  281.          *  
  282.          * ICC卡是否存在 
  283.          */  
  284.         public static boolean hasIccCard;// boolean  
  285.   
  286.         /** 
  287.          *  
  288.          * 是否漫遊: 
  289.          *  
  290.          * (在GSM用途下) 
  291.          */  
  292.         public static boolean isNetworkRoaming;  
  293.     }  
  294.   
  295.     /** 
  296.      * 獲取手機惟一ID 
  297.      *  
  298.      * @param context 
  299.      * @return 
  300.      */  
  301.     public static String getPhoneUniqueId(Context context) {  
  302.         TelephonyManager tm = (TelephonyManager) context  
  303.                 .getSystemService(context.TELEPHONY_SERVICE);  
  304.         return tm.getDeviceId();  
  305.     }  
  306.   
  307.     /** 
  308.      * 獲取手機信息實體 
  309.      *  
  310.      * @param context 
  311.      * @return 
  312.      */  
  313.     public static TelephonyManagerInfo getTelephonyInfo(Context context) {  
  314.         TelephonyManagerInfo info = new TelephonyManagerInfo();  
  315.         TelephonyManager tm = (TelephonyManager) context  
  316.                 .getSystemService(context.TELEPHONY_SERVICE);  
  317.         info.CallState = tm.getCallState();  
  318.         info.CellLocation = tm.getCellLocation().toString();  
  319.         info.DeviceId = tm.getDeviceId();  
  320.         info.DeviceSoftwareVersion = tm.getDeviceSoftwareVersion();  
  321.         info.hasIccCard = tm.hasIccCard();  
  322.         info.isNetworkRoaming = tm.isNetworkRoaming();  
  323.         info.Line1Number = tm.getLine1Number();  
  324.         info.NeighboringCellInfo = tm.getNeighboringCellInfo();  
  325.         info.NetworkCountryIso = tm.getNetworkCountryIso();  
  326.         info.NetworkOperator = tm.getNetworkOperator();  
  327.         info.NetworkOperatorName = tm.getNetworkOperatorName();  
  328.         info.NetworkType = tm.getNetworkType();  
  329.         info.PhoneType = tm.getPhoneType();  
  330.         info.SimCountryIso = tm.getSimCountryIso();  
  331.         info.SimOperator = tm.getSimOperator();  
  332.         info.SimOperatorName = tm.getSimOperatorName();  
  333.         info.SimSerialNumber = tm.getSimSerialNumber();  
  334.         info.SimState = tm.getSimState();  
  335.         info.SubscriberId = tm.getSubscriberId();  
  336.         info.VoiceMailAlphaTag = tm.getVoiceMailAlphaTag();  
  337.         info.VoiceMailNumber = tm.getVoiceMailNumber();  
  338.         return info;  
  339.     }  
  340.   
  341.     /** 
  342.      * 取得屏幕分辨率大小 
  343.      *  
  344.      * @param context 
  345.      *            Activity上下文 
  346.      * @return第一個值爲寬度 
  347.      */  
  348.     public static int[] getDisplayPixes(Activity context) {  
  349.         DisplayMetrics dm = new DisplayMetrics();  
  350.         context.getWindowManager().getDefaultDisplay().getMetrics(dm);  
  351.         return new int[] { dm.widthPixels, dm.heightPixels };  
  352.     }  
  353.   
  354.     /** 
  355.      * 取得屏幕分辨寬度和高度 
  356.      *  
  357.      * @param context 
  358.      *            Activity上下文 
  359.      * @return第一個值爲寬度 
  360.      */  
  361.     public static int[] getDisplayWidthHeight(Activity context) {  
  362.         Display dis = context.getWindowManager().getDefaultDisplay();  
  363.         return new int[] { dis.getWidth(), dis.getHeight() };  
  364.     }  
  365.   
  366.     /** 
  367.      * 檢查是否有可用的網絡 
  368.      *  
  369.      * @param context 
  370.      *            上下文 
  371.      * @return true:有網絡 
  372.      */  
  373.     public static boolean isAvaliable(Context context) {  
  374.         if (isWiFiActive(context) || isNetworkAvailable(context))  
  375.             // Toast.makeText(context, "有網絡!", 300).show();  
  376.             return true;  
  377.         else  
  378.             // Toast.makeText(context, "網絡不正常!", 300).show();  
  379.             return false;  
  380.     }  
  381.   
  382.     /** 返回當前網速 */  
  383.     public static long getNetworkSpeed() {  
  384.         // TODO Auto-generated method stub  
  385.         ProcessBuilder cmd;  
  386.         long readBytes = 0;  
  387.         BufferedReader rd = null;  
  388.         try {  
  389.             String[] args = { "/system/bin/cat""/proc/net/dev" };  
  390.             cmd = new ProcessBuilder(args);  
  391.             Process process = cmd.start();  
  392.             rd = new BufferedReader(new InputStreamReader(  
  393.                     process.getInputStream()));  
  394.             String line;  
  395.             int linecount = 0;  
  396.             while ((line = rd.readLine()) != null) {  
  397.                 linecount++;  
  398.                 if (line.contains("wlan0") || line.contains("eth0")) {  
  399.                     // L.E("獲取流量整條字符串",line);  
  400.                     String[] delim = line.split(":");  
  401.                     if (delim.length >= 2) {  
  402.                         String[] numbers = delim[1].trim().split(" ");// 提取數據  
  403.                         readBytes = Long.parseLong(numbers[0].trim());//  
  404.                         break;  
  405.                     }  
  406.                 }  
  407.             }  
  408.             rd.close();  
  409.         } catch (Exception ex) {  
  410.             ex.printStackTrace();  
  411.         } finally {  
  412.             if (rd != null) {  
  413.                 try {  
  414.                     rd.close();  
  415.                 } catch (IOException e) {  
  416.                     // TODO Auto-generated catch block  
  417.                     e.printStackTrace();  
  418.                 }  
  419.             }  
  420.         }  
  421.         return readBytes;  
  422.     }  
  423.   
  424.     /** 
  425.      * 檢查wifi是否可用 
  426.      *  
  427.      * @param inContext 
  428.      * @return 
  429.      */  
  430.     public static boolean isWiFiActive(Context inContext) {  
  431.         WifiManager mWifiManager = (WifiManager) inContext  
  432.                 .getSystemService(Context.WIFI_SERVICE);  
  433.         WifiInfo wifiInfo = mWifiManager.getConnectionInfo();  
  434.         int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();  
  435.         if (mWifiManager.isWifiEnabled() && ipAddress != 0) {  
  436.             System.out.println("**** WIFI is on");  
  437.             return true;  
  438.         } else {  
  439.             System.out.println("**** WIFI is off");  
  440.             return false;  
  441.         }  
  442.     }  
  443.   
  444.     /** 
  445.      * 檢查手機網絡(非wifi)是否有用 
  446.      *  
  447.      * @param context 
  448.      * @return 
  449.      */  
  450.     public static boolean isNetworkAvailable(Context context) {  
  451.         ConnectivityManager connectivity = (ConnectivityManager) context  
  452.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  453.         if (connectivity == null) {  
  454.             return false;  
  455.         } else {  
  456.             NetworkInfo info = connectivity.getActiveNetworkInfo();  
  457.             if (info == null) {  
  458.                 return false;  
  459.             } else {  
  460.                 if (info.isAvailable()) {  
  461.                     return true;  
  462.                 }  
  463.             }  
  464.         }  
  465.         return false;  
  466.     }  
  467.   
  468.     /** 
  469.      * 判斷是否爲wifi的鏈接ip 
  470.      *  
  471.      * @return 
  472.      */  
  473.     public static boolean isWifiConnected(Context context) {  
  474.         int ipAddress = getWifiIpInfo(context);  
  475.         if (ipAddress > 0)  
  476.             return true;  
  477.         else  
  478.             return false;  
  479.     }  
  480.   
  481.     private static int getWifiIpInfo(Context context) {  
  482.         // 獲取wifi服務  
  483.         WifiManager wifiManager = (WifiManager) context  
  484.                 .getSystemService(Context.WIFI_SERVICE);  
  485.         // 判斷wifi是否開啓  
  486.         if (!wifiManager.isWifiEnabled()) {  
  487.             wifiManager.setWifiEnabled(true);  
  488.         }  
  489.         WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
  490.         // return String.valueOf(wifiInfo.getIpAddress());  
  491.         int ipAddress = wifiInfo.getIpAddress();  
  492.         return ipAddress;  
  493.     }  
  494.   
  495.     /** 
  496.      * 獲取wifi ip 
  497.      *  
  498.      * @return 
  499.      */  
  500.     public static String getWifiAddress(Context context) {  
  501.         int ipAddress = getWifiIpInfo(context);  
  502.         return intToIp(ipAddress);  
  503.     }  
  504.   
  505.     private static String intToIp(int i) {  
  506.         return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)  
  507.                 + "." + (i >> 24 & 0xFF);  
  508.     }  
  509.   
  510.     /** 
  511.      * 獲取手機mac地址<br/> 
  512.      * 錯誤返回12個0 
  513.      */  
  514.     public static String getMacAddress(Context context) {  
  515.         // 獲取mac地址:  
  516.         String macAddress = "000000000000";  
  517.         try {  
  518.             WifiManager wifiMgr = (WifiManager) context  
  519.                     .getSystemService(Context.WIFI_SERVICE);  
  520.             WifiInfo info = (null == wifiMgr ? null : wifiMgr  
  521.                     .getConnectionInfo());  
  522.             if (null != info) {  
  523.                 if (!TextUtils.isEmpty(info.getMacAddress()))  
  524.                     macAddress = info.getMacAddress().replace(":""");  
  525.                 else  
  526.                     return macAddress;  
  527.             }  
  528.         } catch (Exception e) {  
  529.             // TODO Auto-generated catch block  
  530.             e.printStackTrace();  
  531.             return macAddress;  
  532.         }  
  533.         return macAddress;  
  534.     }  
  535.   
  536.     /** 
  537.      * 獲取手機ip(此方法在android中使用獲取3G網絡ip地址) 
  538.      *  
  539.      * @return 
  540.      * @throws SocketException 
  541.      * @throws UnknownHostException 
  542.      */  
  543.     public static String getLocalIpAddress() throws SocketException {  
  544.         for (Enumeration<NetworkInterface> en = NetworkInterface  
  545.                 .getNetworkInterfaces(); en.hasMoreElements();) {  
  546.             NetworkInterface intf = en.nextElement();  
  547.             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr  
  548.                     .hasMoreElements();) {  
  549.                 InetAddress inetAddress = enumIpAddr.nextElement();  
  550.                 if (!inetAddress.isLoopbackAddress()) {  
  551.                     return inetAddress.getHostAddress().toString();  
  552.                 }  
  553.             }  
  554.         }  
  555.         return null;  
  556.     }  
  557.   
  558.     /** 
  559.      * 獲取本機ip(此方法僅在java程序中) 
  560.      *  
  561.      * @return 
  562.      * @throws UnknownHostException 
  563.      */  
  564.     public static String getHostAddress() throws UnknownHostException {  
  565.         InetAddress address = null;  
  566.         address = InetAddress.getLocalHost();  
  567.         return address.getHostAddress();  
  568.     }  
  569.   
  570.     /** 
  571.      * 讀取文本,一次讀取多個字節,默認爲1024 
  572.      *  
  573.      * @param file 
  574.      *            文件名稱(在sd卡下面的data/data/應用程序包下面) 
  575.      * @param context 
  576.      *            上下文 
  577.      * @param encode 
  578.      *            編碼方式 
  579.      * @return 
  580.      * @throws IOException 
  581.      */  
  582.     public static String readFromFileByChar(String file, Context context,  
  583.             String encode) throws IOException {  
  584.         FileInputStream fis = context.openFileInput(file);  
  585.         BufferedReader br = new BufferedReader(new InputStreamReader(fis,  
  586.                 encode));  
  587.         // Log.i(TAG, br.readLine());  
  588.         int index = 0;  
  589.         char[] buffer = new char[1024];// 一次性讀取1024個字符  
  590.         StringBuffer sb = new StringBuffer();  
  591.         while ((index = br.read(buffer)) != -1) {// 一次讀多個字符  
  592.             // 一樣屏蔽掉r不顯示  
  593.             if ((index == buffer.length) && (buffer[buffer.length - 1] != 'r')) {  
  594.                 sb.append(buffer);  
  595.             } else {  
  596.                 for (int i = 0; i < index; i++) {  
  597.                     if (buffer[i] == 'r') {  
  598.                         continue;// 中止執行當前的迭代,而後退回循環開始處  
  599.                     } else {  
  600.                         sb.append(buffer[i]);  
  601.                     }  
  602.                 }  
  603.             }  
  604.         }  
  605.         br.close();  
  606.         fis.close();  
  607.         return sb.toString();  
  608.         // return br.readLine();  
  609.     }  
  610.   
  611.     /** 
  612.      * 按行讀取文本 
  613.      *  
  614.      * @param file 
  615.      *            文件名 
  616.      * @param context 
  617.      *            上下文 
  618.      * @param encode 
  619.      *            編碼方式 
  620.      * @return 
  621.      * @throws IOException 
  622.      */  
  623.     public static String readFromFileByLine(String file, Context context,  
  624.             String encode) throws IOException {  
  625.         FileInputStream fis = context.openFileInput(file);  
  626.         BufferedReader br = new BufferedReader(new InputStreamReader(fis,  
  627.                 encode));  
  628.         // Log.i(TAG, br.readLine());  
  629.         StringBuffer sb = new StringBuffer();  
  630.         String temp;  
  631.         while ((temp = br.readLine()) != null) {// 一次讀一行  
  632.             sb.append(temp);  
  633.         }  
  634.         br.close();  
  635.         fis.close();  
  636.         return sb.toString();  
  637.         // return br.readLine();  
  638.     }  
  639.   
  640.     /** 
  641.      * 一次將string內容寫入到文件 
  642.      *  
  643.      * @param context 
  644.      *            上下文 
  645.      * @param file 
  646.      *            文件名 
  647.      * @param content 
  648.      *            寫入的內容 
  649.      * @throws IOException 
  650.      */  
  651.     public static void writeToFile(Context context, String file, String content)  
  652.             throws IOException {  
  653.         FileOutputStream fos = context.openFileOutput(file,  
  654.                 context.MODE_PRIVATE);  
  655.         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));  
  656.         bw.write(content);  
  657.         bw.flush();  
  658.         bw.close();  
  659.         fos.close();  
  660.     }  
  661.   
  662.     /** 
  663.      * 將object序列化到filename文件中 
  664.      *  
  665.      * @param fileName 
  666.      *            文件名,包括路徑 
  667.      * @param object 
  668.      *            序列化的對象 
  669.      */  
  670.     public static boolean writeFileByObject(String fileName, Object object) {  
  671.         try {  
  672.             FileOutputStream fos = new FileOutputStream(fileName);  
  673.             ObjectOutputStream oos = new ObjectOutputStream(fos);  
  674.             oos.writeObject(object);  
  675.             oos.flush();  
  676.             oos.close();  
  677.             fos.close();  
  678.             return true;  
  679.         } catch (Exception e) {  
  680.             e.printStackTrace();  
  681.             return false;  
  682.         }  
  683.     }  
  684.   
  685.     /** 
  686.      * 反序列化 
  687.      *  
  688.      * @param fileName 
  689.      *            文件名,包括詳細路徑 
  690.      * @return Object類型的對象 
  691.      */  
  692.     public static Object readFileByObject(String fileName) {  
  693.         try {  
  694.             FileInputStream fis = new FileInputStream(fileName);  
  695.             ObjectInputStream ois = new ObjectInputStream(fis);  
  696.             Object o = ois.readObject();  
  697.             ois.close();  
  698.             fis.close();  
  699.             return o;  
  700.         } catch (Exception e) {  
  701.             return null;  
  702.         }  
  703.     }  
  704.   
  705.     /** 
  706.      * 按照指定的寬度和高度壓縮圖片(這是android 2.2以上纔有的方法) 
  707.      *  
  708.      * @param bm 
  709.      * @param w 
  710.      * @param h 
  711.      * @return 
  712.      */  
  713.     public static Bitmap compressBitmap(Bitmap bm, int w, int h) {  
  714.         return ThumbnailUtils.extractThumbnail(bm, w, h);  
  715.     }  
  716.   
  717.     /** 
  718.      * 等比例壓縮圖片 
  719.      *  
  720.      * @param is 
  721.      *            圖片輸入流 
  722.      * @param scalePix 
  723.      *            壓縮的尺寸 
  724.      * @return 
  725.      */  
  726.     public static Bitmap compressBitmapByscale(InputStream is, int scalePix) {  
  727.         BitmapFactory.Options opt = new Options();  
  728.         opt.inSampleSize = scalePix;  
  729.         return BitmapFactory.decodeStream(is, null, opt);  
  730.     }  
  731.   
  732.     /** 
  733.      * 等比例壓縮圖片 
  734.      *  
  735.      * @param data 
  736.      *            byte[]數組 
  737.      *  
  738.      * @param ratio 
  739.      *            壓縮的尺寸 
  740.      * @return 
  741.      */  
  742.     public static Bitmap compressBitmap(byte[] data, int ratio) {  
  743.         BitmapFactory.Options opts = new Options();  
  744.         opts.inJustDecodeBounds = false;  
  745.         opts.inSampleSize = ratio;  
  746.         // 獲得新的圖片  
  747.         return BitmapFactory.decodeByteArray(data, 0, data.length, opts);  
  748.   
  749.     }  
  750.   
  751.     /** 
  752.      * 自動壓縮圖片(根據可以壓縮的比例) 
  753.      *  
  754.      * @param map 
  755.      * @return 
  756.      */  
  757.     public static Bitmap compressBitmapAuto(Bitmap map, int scalePix) {  
  758.         BitmapFactory.Options opts = new BitmapFactory.Options();  
  759.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  760.         byte[] data = os.toByteArray();  
  761.         opts.inJustDecodeBounds = true;  
  762.         map.compress(CompressFormat.PNG, 100, os);  
  763.         Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
  764.         opts.inJustDecodeBounds = false;  
  765.         int be = (int) (opts.outHeight / (float) scalePix);  
  766.         if (be <= 0)  
  767.             be = 1;  
  768.         opts.inSampleSize = be;  
  769.         bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);  
  770.         return bitmap;  
  771.     }  
  772.   
  773.     /** 根據屏幕大小適屏壓縮 --2012/11/13-- */  
  774.     public static Bitmap compressBitmapFixDisplay(Activity context, byte[] data) {  
  775.         BitmapFactory.Options opts = new Options();  
  776.         opts.inJustDecodeBounds = true;// 設置查看圖片的大小,不分配內存  
  777.         BitmapFactory.decodeByteArray(data, 0, data.length, opts);  
  778.         int height = context.getWindowManager().getDefaultDisplay().getHeight();// 獲取屏幕大小  
  779.         int width = context.getWindowManager().getDefaultDisplay().getWidth();  
  780.         int hratio = (int) Math.ceil(opts.outHeight / (float) height);// 圖片的高度比上屏幕的高度  
  781.         int wratio = (int) Math.ceil(opts.outWidth / (float) width);  
  782.         if (hratio > 1 || wratio > 1) {// 若是圖片超出屏幕範圍  
  783.             if (hratio > wratio)// 若是高度大於寬度  
  784.                 opts.inSampleSize = hratio;  
  785.             else  
  786.                 opts.inSampleSize = wratio;  
  787.         }  
  788.         opts.inJustDecodeBounds = false;// 設置分配圖片的大小  
  789.         Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,  
  790.                 opts);  
  791.         return bitmap;  
  792.     }  
  793.   
  794.     /** 
  795.      * 壓縮圖片 
  796.      *  
  797.      * @param bm 
  798.      *            所要轉換的bitmap 
  799.      * @param newWidth新的寬 
  800.      * @param newHeight新的高 
  801.      * @return 指定寬高的bitmap 
  802.      */  
  803.     public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {  
  804.         // 得到圖片的寬高  
  805.         int width = bm.getWidth();  
  806.         int height = bm.getHeight();  
  807.         // 計算縮放比例  
  808.         float scaleWidth = ((float) newWidth) / width;  
  809.         float scaleHeight = ((float) newHeight) / height;  
  810.         // 取得想要縮放的matrix參數  
  811.         Matrix matrix = new Matrix();  
  812.         matrix.postScale(scaleWidth, scaleHeight);  
  813.         // 獲得新的圖片  
  814.         Bitmap newbm = Bitmap.createBitmap(bm, 00, width, height, matrix,  
  815.                 true);  
  816.         if (!bm.isRecycled())// 回收bitmap  
  817.             bm.recycle();  
  818.         return newbm;  
  819.     }  
  820.   
  821.     /** 
  822.      * 動態設置ImageView的佈局寬度和高度 
  823.      *  
  824.      * @param iv 
  825.      *            ImageView對象 
  826.      * @param width 
  827.      *            要設置的寬度(0:充滿父容器) 
  828.      * @param height 
  829.      *            要設置的高度(0:充滿父容器) 
  830.      */  
  831.     public static void setImagePixes(ImageView iv, int width, int height) {  
  832.         ViewGroup.LayoutParams params = iv.getLayoutParams();  
  833.         if (width == 0 && height != 0)// 若是寬度爲0  
  834.         {  
  835.             params.height = height;  
  836.             params.width = ViewGroup.LayoutParams.FILL_PARENT;  
  837.         } else if (height == 0 && width != 0) {// 高度爲 0  
  838.             params.height = ViewGroup.LayoutParams.FILL_PARENT;  
  839.             params.width = width;  
  840.         } else if (width == 0 && height == 0) {  
  841.             params.height = ViewGroup.LayoutParams.FILL_PARENT;  
  842.             params.width = ViewGroup.LayoutParams.FILL_PARENT;  
  843.         } else {  
  844.             params.height = height;  
  845.             params.width = width;  
  846.         }  
  847.         iv.setLayoutParams(params);  
  848.     }  
  849.   
  850.     /** activity轉換爲view */  
  851.     @SuppressWarnings("deprecation")  
  852.     public static View activityToView(Context parent, Intent intent) {  
  853.         LocalActivityManager mLocalActivityManager = new LocalActivityManager(  
  854.                 (Activity) parent, true);  
  855.         final Window w = mLocalActivityManager.startActivity("TagName", intent);  
  856.         final View wd = w != null ? w.getDecorView() : null;  
  857.         if (wd != null) {  
  858.             wd.setVisibility(View.VISIBLE);  
  859.             wd.setFocusableInTouchMode(true);  
  860.             ((ViewGroup) wd)  
  861.                     .setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);  
  862.         }  
  863.         return wd;  
  864.     }  
  865.   
  866.     /*** 
  867.      * 動態設置listview的高度 
  868.      *  
  869.      * @param listView 
  870.      */  
  871.     public static void setListViewHeightBasedOnChildren(ListView listView) {  
  872.         ListAdapter listAdapter = listView.getAdapter();  
  873.         if (listAdapter == null) {  
  874.             return;  
  875.         }  
  876.         int totalHeight = 0;  
  877.         for (int i = 0; i < listAdapter.getCount(); i++) {  
  878.             View listItem = listAdapter.getView(i, null, listView);  
  879.             listItem.measure(00);  
  880.             totalHeight += listItem.getMeasuredHeight();  
  881.         }  
  882.         ViewGroup.LayoutParams params = listView.getLayoutParams();  
  883.         params.height = totalHeight  
  884.                 + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
  885.         // params.height += 5;// if without this statement,the listview will be  
  886.         // a  
  887.         // little short  
  888.         // listView.getDividerHeight()獲取子項間分隔符佔用的高度  
  889.         // params.height最後獲得整個ListView完整顯示須要的高度  
  890.         listView.setLayoutParams(params);  
  891.     }  
  892.   
  893.     /** 
  894.      * 將Drawable轉化爲Bitmap 
  895.      *  
  896.      * @param drawable 
  897.      * @return 
  898.      */  
  899.     public static Bitmap drawableToBitmap(Drawable drawable) {  
  900.         int width = drawable.getIntrinsicWidth();  
  901.         int height = drawable.getIntrinsicHeight();  
  902.         Bitmap bitmap = Bitmap.createBitmap(width, height, drawable  
  903.                 .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
  904.                 : Bitmap.Config.RGB_565);  
  905.         Canvas canvas = new Canvas(bitmap);  
  906.         drawable.setBounds(00, width, height);  
  907.         drawable.draw(canvas);  
  908.         return bitmap;  
  909.     }  
  910.   
  911.     /** 
  912.      * 將圖片的四角圓化 
  913.      *  
  914.      * @param bitmap 
  915.      * @param radius 
  916.      *            圓角弧度,數值越大弧度越大 
  917.      * @return 
  918.      */  
  919.     public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int radius) {  
  920.   
  921.         Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),  
  922.                 bitmap.getHeight(), Config.ARGB_8888);  
  923.         // 獲得畫布  
  924.         Canvas canvas = new Canvas(output);  
  925.   
  926.         // 將畫布的四角圓化  
  927.         final int color = Color.RED;  
  928.         final Paint paint = new Paint();  
  929.         // 獲得與圖像相同大小的區域 由構造的四個值決定區域的位置以及大小  
  930.         final Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());  
  931.         final RectF rectF = new RectF(rect);  
  932.         // 值越大角度越明顯  
  933.         final float roundPx = radius;  
  934.   
  935.         paint.setAntiAlias(true);  
  936.         canvas.drawARGB(0000);  
  937.         paint.setColor(color);  
  938.         // drawRoundRect的第2,3個參數同樣則畫的是正圓的一角,若是數值不一樣則是橢圓的一角  
  939.         canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  
  940.   
  941.         paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // 設置形式爲背景  
  942.         canvas.drawBitmap(bitmap, rect, rect, paint);  
  943.   
  944.         return output;  
  945.     }  
  946.   
  947.     /** 
  948.      * 得到帶倒影的圖片方法 
  949.      *  
  950.      * @param bitmap 
  951.      * @return 
  952.      */  
  953.     public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {  
  954.         final int reflectionGap = 4;  
  955.         int width = bitmap.getWidth();  
  956.         int height = bitmap.getHeight();  
  957.         Matrix matrix = new Matrix();  
  958.         matrix.preScale(1, -1);  
  959.         Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,  
  960.                 width, height / 2, matrix, false);  
  961.         Bitmap bitmapWithReflection = Bitmap.createBitmap(width,  
  962.                 (height + height / 2), Config.ARGB_8888);  
  963.         Canvas canvas = new Canvas(bitmapWithReflection);  
  964.         canvas.drawBitmap(bitmap, 00null);  
  965.         Paint deafalutPaint = new Paint();  
  966.         canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);  
  967.         canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);  
  968.         Paint paint = new Paint();  
  969.         LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,  
  970.                 bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,  
  971.                 0x00ffffff, TileMode.CLAMP);  
  972.         paint.setShader(shader);// 設置陰影  
  973.         // Set the Transfer mode to be porter duff and destination in  
  974.         paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));  
  975.         // Draw a rectangle using the paint with our linear gradient  
  976.         canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()  
  977.                 + reflectionGap, paint);  
  978.         return bitmapWithReflection;  
  979.     }  
  980.   
  981.     /** 
  982.      * 向preferences寫入數據 
  983.      *  
  984.      * @param context 
  985.      *            上下文 
  986.      * @param key 
  987.      *            鍵 
  988.      * @param value 
  989.      *            寫入的內容 
  990.      */  
  991.     public static void writeToPreferences(Context context, String filename,  
  992.             String key, String value) {  
  993.         // 獲得preferences對象  
  994.         SharedPreferences.Editor editor = context.getSharedPreferences(  
  995.                 filename, android.content.Context.MODE_PRIVATE).edit();  
  996.         // editor = preferences.edit();  
  997.         editor.putString(key, value);  
  998.         editor.commit();  
  999.     }  
  1000.   
  1001.     /** 
  1002.      * 向preference中讀取數據 data/data/package/shared_prefs 
  1003.      *  
  1004.      * @param context 
  1005.      *            上下文 
  1006.      * @param filename 
  1007.      *            文件名 
  1008.      * @param key 
  1009.      *            鍵 
  1010.      * @param defaultValue 
  1011.      *            默認值 
  1012.      * @return 
  1013.      */  
  1014.     public static String readFromPreferences(Context context, String filename,  
  1015.             String key, String defaultValue) {  
  1016.         // 獲得preferences對象  
  1017.         SharedPreferences preferences = context.getSharedPreferences(filename,  
  1018.                 android.content.Context.MODE_PRIVATE  
  1019.                         | android.content.Context.MODE_APPEND);  
  1020.         return preferences.getString(key, defaultValue);  
  1021.     }  
  1022.   
  1023.     /** 
  1024.      * 加載properties文件 
  1025.      *  
  1026.      * @param context 
  1027.      * @param file 
  1028.      * @return 
  1029.      * @throws Exception 
  1030.      */  
  1031.     public static Properties loadProperties(Context context, String file,  
  1032.             String encode) throws Exception {  
  1033.         Properties properties = new Properties();  
  1034.         FileInputStream s = new FileInputStream(file);  
  1035.         properties.load(s);  
  1036.         return properties;  
  1037.     }  
  1038.   
  1039.     /** 
  1040.      * 保存到properties文件中 
  1041.      *  
  1042.      * @param context 
  1043.      * @param file 
  1044.      * @param properties 
  1045.      * @throws Exception 
  1046.      */  
  1047.     public static void saveProperties(Context context, String file,  
  1048.             String encode, Properties properties) throws Exception {  
  1049.         FileOutputStream s = new FileOutputStream(file, false);  
  1050.         properties.store(s, "");  
  1051.     }  
  1052.   
  1053.     // ---------------------------------------------------------------------------------------------------  
  1054.   
  1055.     /** 
  1056.      * 從網絡上下載 
  1057.      *  
  1058.      * @param url 
  1059.      * @return 
  1060.      * @throws IOException 
  1061.      */  
  1062.     public static Bitmap getBitMapFromUrl(String url) throws IOException {  
  1063.         Bitmap bitmap = null;  
  1064.         URL u = null;  
  1065.         HttpURLConnection conn = null;  
  1066.         InputStream is = null;  
  1067.         u = new URL(url);  
  1068.         conn = (HttpURLConnection) u.openConnection();  
  1069.         is = conn.getInputStream();  
  1070.         bitmap = BitmapFactory.decodeStream(is);  
  1071.         return bitmap;  
  1072.     }  
  1073.   
  1074.     /** 
  1075.      * 異步加載網絡圖片 
  1076.      *  
  1077.      * @param src圖片路徑 
  1078.      * @param iv 
  1079.      *            imageview 
  1080.      * @param callback回調接口 
  1081.      */  
  1082.     public static void loadImage(final String src, final ImageView iv,  
  1083.             final ImageCallBack callback) {  
  1084.         final Handler handler = new Handler() {  
  1085.             public void handleMessage(Message msg) {  
  1086.                 super.handleMessage(msg);  
  1087.                 callback.setImageBitmap((Bitmap) msg.obj, iv, src);  
  1088.             }  
  1089.         };  
  1090.         new Thread(new Runnable() {  
  1091.             @Override  
  1092.             public void run() {  
  1093.                 Bitmap bitmap = null;  
  1094.                 try {  
  1095.                     bitmap = getBitMapFromUrl(src);  
  1096.                 } catch (IOException e) {  
  1097.                     e.printStackTrace();  
  1098.                 }  
  1099.                 if (bitmap != null) {  
  1100.                     Message msg = handler.obtainMessage(0, bitmap);  
  1101.                     handler.sendMessage(msg);  
  1102.                 }  
  1103.             }  
  1104.         }).start();  
  1105.     }  
  1106.   
  1107.     /** 
  1108.      * 獲取網絡byte流的圖片 
  1109.      *  
  1110.      * @param src 
  1111.      * @return 
  1112.      * @throws Exception 
  1113.      */  
  1114.     public static byte[] getImageBytes(String src) throws Exception {  
  1115.         URL url = new URL(src);  
  1116.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  1117.         conn.setDoInput(true);  
  1118.         conn.setRequestMethod("GET");  
  1119.         conn.setConnectTimeout(5000);// 設置延遲時間爲5s  
  1120.         InputStream is = conn.getInputStream();  
  1121.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  1122.         int len = 0;  
  1123.         byte[] buffer = new byte[1024];  
  1124.         while ((len = is.read(buffer)) != -1) {  
  1125.             bos.write(buffer, 0, len);  
  1126.         }  
  1127.         return bos.toByteArray();  
  1128.     }  
  1129.   
  1130.     /** 
  1131.      * 壓縮圖片 
  1132.      *  
  1133.      * @param bm 
  1134.      *            所要轉換的bitmap 
  1135.      * @param newWidth新的寬 
  1136.      * @param newHeight新的高 
  1137.      * @return 指定寬高的bitmap 
  1138.      */  
  1139.     public static Bitmap zoomBitmap(byte[] data, int newWidth, int newHeight) {  
  1140.         BitmapFactory.Options opts = new Options();  
  1141.         opts.inJustDecodeBounds = false;  
  1142.         opts.inSampleSize = 10;  
  1143.         // 獲得新的圖片  
  1144.         Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,  
  1145.                 opts);  
  1146.         // 得到圖片的寬高  
  1147.         int width = bitmap.getWidth();  
  1148.         int height = bitmap.getHeight();  
  1149.         // 計算縮放比例  
  1150.         float scaleWidth = ((float) newWidth) / width;  
  1151.         float scaleHeight = ((float) newHeight) / height;  
  1152.         // 取得想要縮放的matrix參數  
  1153.         Matrix matrix = new Matrix();  
  1154.         matrix.postScale(scaleWidth, scaleHeight);  
  1155.   
  1156.         Bitmap newbm = Bitmap.createBitmap(bitmap, 00, width, height, matrix,  
  1157.                 true);  
  1158.         if (!bitmap.isRecycled())// 回收bitmap  
  1159.             bitmap.recycle();  
  1160.         return newbm;  
  1161.     }  
  1162.   
  1163.     /** 
  1164.      * 異步加載網絡圖片 
  1165.      *  
  1166.      * @param src 
  1167.      *            url地址 
  1168.      * @param iv 
  1169.      *            傳入的iamgeView 
  1170.      * @param callback 
  1171.      *            回調函數 
  1172.      */  
  1173.     public static void AsycloadImage(final String src, final ImageView iv,  
  1174.             final ImageCallBack callback) {  
  1175.         final Handler handler = new Handler() {  
  1176.             public void handleMessage(Message msg) {  
  1177.                 super.handleMessage(msg);  
  1178.                 callback.setImageBitmap((Bitmap) msg.obj, iv, src);  
  1179.             }  
  1180.         };  
  1181.         new Thread(new Runnable() {  
  1182.             @Override  
  1183.             public void run() {  
  1184.                 byte[] data = null;  
  1185.                 Bitmap bitmap = null;  
  1186.                 try {  
  1187.                     data = getImageBytes(src);  
  1188.                     bitmap = compressBitmap(data, 3);  
  1189.   
  1190.                 } catch (Exception e) {  
  1191.                     e.printStackTrace();  
  1192.                 }  
  1193.                 if (bitmap != null) {  
  1194.                     Message msg = handler.obtainMessage(0, bitmap);  
  1195.                     handler.sendMessage(msg);  
  1196.                 }  
  1197.             }  
  1198.         }).start();  
  1199.     }  
  1200.   
  1201.     /** 
  1202.      * 異步加載圖片 
  1203.      *  
  1204.      * @param url 
  1205.      *            圖片路徑 
  1206.      * @param iv 
  1207.      *            ImageView 
  1208.      * @param imgCache 
  1209.      *            緩存 
  1210.      * @param callback 
  1211.      *            回調接口 
  1212.      */  
  1213.     public static void AyncLoadImageFromUrl(final String url,  
  1214.             final ImageView iv,  
  1215.             final Map<String, SoftReference<Bitmap>> imgCache,  
  1216.             final ImageCallBack callback) {  
  1217.         if (imgCache.containsKey(url))// 若是緩存中存在  
  1218.         {  
  1219.             iv.setImageBitmap(imgCache.get(url).get());  
  1220.             return;  
  1221.         }  
  1222.         final Handler handler = new Handler() {  
  1223.             public void handleMessage(Message msg) {  
  1224.                 super.handleMessage(msg);  
  1225.                 callback.setImageBitmap((Bitmap) msg.obj, iv, url);  
  1226.             }  
  1227.         };  
  1228.         new Thread(new Runnable() {  
  1229.   
  1230.             @Override  
  1231.             public void run() {  
  1232.                 byte[] data = null;  
  1233.                 Bitmap bitmap = null;  
  1234.                 try {  
  1235.                     data = getImageBytes(url);  
  1236.                     bitmap = compressBitmap(data, 3);  
  1237.                 } catch (Exception e) {  
  1238.                     e.printStackTrace();  
  1239.                 }  
  1240.                 if (bitmap != null) {  
  1241.                     // 保存到緩存中  
  1242.                     // 將圖片保存到緩存中  
  1243.                     imgCache.put(url, new SoftReference<Bitmap>(bitmap));  
  1244.                     Message msg = handler.obtainMessage(0, bitmap);  
  1245.                     handler.sendMessage(msg);  
  1246.                 }  
  1247.             }  
  1248.         }).start();  
  1249.     }  
  1250.   
  1251.     /** 
  1252.      * 保存圖片到sdcard,而且返回圖片名稱,帶後綴名 
  1253.      *  
  1254.      * @param context 
  1255.      * @param fileName 
  1256.      *            圖片目錄名稱 
  1257.      * @param photo 
  1258.      *            圖片路徑 
  1259.      * @throws IOException 
  1260.      */  
  1261.     public static String saveImgToSdcard(Context context, String fileName,  
  1262.             String photo) throws IOException {  
  1263.         String url = photo;  
  1264.         // 獲取圖片名稱,包含後綴  
  1265.         String imgName = url.substring(url.lastIndexOf("/") + 1, url.length());  
  1266.         URL Url = new URL(url);  
  1267.         HttpURLConnection conn = (HttpURLConnection) Url.openConnection();  
  1268.         InputStream is = conn.getInputStream();  
  1269.         String saveUrl = context.getFilesDir() + "/" + fileName + "/" + imgName;  
  1270.         File file = new File(saveUrl);  
  1271.         // 若是圖片文件存在  
  1272.         if (file.exists())  
  1273.             return imgName;  
  1274.         FileOutputStream fos = new FileOutputStream(file);  
  1275.         byte[] data = new byte[512];  
  1276.         int len = 0;  
  1277.         while ((len = is.read(data)) != -1) {  
  1278.             fos.write(data, 0, len);  
  1279.         }  
  1280.         fos.flush();  
  1281.         fos.close();  
  1282.         return imgName;  
  1283.     }  
  1284.   
  1285.     /** 
  1286.      * 保存圖片到指定的目錄 
  1287.      *  
  1288.      * @param context 
  1289.      *            上下文 
  1290.      * @param filedir 
  1291.      *            圖片目錄名稱 
  1292.      * @param name 
  1293.      *            圖片名稱 
  1294.      * @param bitmap 
  1295.      *            圖片 
  1296.      * @throws Exception 
  1297.      */  
  1298.     public static void saveBitmapToSdcard(Context context, String filedir,  
  1299.             String name, Bitmap bitmap) throws Exception {  
  1300.         String path = context.getFilesDir() + File.separator + filedir  
  1301.                 + File.separator;  
  1302.         File file = new File(path);  
  1303.         if (!file.exists()) {  
  1304.             file.mkdir();  
  1305.         }  
  1306.         file = new File(path + name + ".png");  
  1307.         if (file.exists())  
  1308.             return;  
  1309.         FileOutputStream fos = new FileOutputStream(file);  
  1310.         bitmap.compress(CompressFormat.PNG, 100, fos);  
  1311.         fos.close();  
  1312.     }  
  1313.   
  1314.     /** 從sdcard制定目錄讀取圖片 */  
  1315.     public static Bitmap getBitmapFromSdcard(Context context, String file,  
  1316.             String name) {  
  1317.         String src = context.getFilesDir() + "/" + file + "/" + name;  
  1318.         Bitmap bitmap = BitmapFactory.decodeFile(src);  
  1319.         return bitmap;  
  1320.     }  
  1321.   
  1322.     /** 
  1323.      * 從緩存中讀取 
  1324.      *  
  1325.      * @param url 
  1326.      * @return 
  1327.      * @throws Exception 
  1328.      */  
  1329.     public static Bitmap getImgFromCache(final String url, final ImageView iv,  
  1330.             final Map<String, SoftReference<Bitmap>> imgCache,  
  1331.             final ImageCallBack callback) throws Exception {  
  1332.         // 從內存中讀取  
  1333.         if (imgCache.containsKey(url)) {  
  1334.             synchronized (imgCache) {  
  1335.                 SoftReference<Bitmap> bitmapReference = imgCache.get(url);  
  1336.                 if (null != bitmapReference) {  
  1337.                     return bitmapReference.get();  
  1338.                 }  
  1339.             }  
  1340.         }  
  1341.         final Handler handler = new Handler() {  
  1342.             @Override  
  1343.             public void handleMessage(Message msg) {  
  1344.                 super.handleMessage(msg);  
  1345.                 callback.setImageBitmap((Bitmap) msg.obj, iv, url);  
  1346.             }  
  1347.         };  
  1348.         // 從網絡中下載  
  1349.         new Thread(new Runnable() {  
  1350.             @Override  
  1351.             public void run() {  
  1352.                 Bitmap bitmap = null;  
  1353.                 try {  
  1354.                     bitmap = getBitMapFromUrl(url);  
  1355.                 } catch (IOException e) {  
  1356.                     e.printStackTrace();  
  1357.                 }  
  1358.                 // 將圖片保存進內存中  
  1359.                 imgCache.put(url, new SoftReference<Bitmap>(bitmap));  
  1360.                 Message msg = handler.obtainMessage(0, bitmap);  
  1361.                 handler.sendMessage(msg);  
  1362.             }  
  1363.         }).start();  
  1364.         return null;  
  1365.     }  
  1366.   
  1367.     public interface ImageCallBack {  
  1368.         public void setImageBitmap(Bitmap bitmap, ImageView iv, String url);  
  1369.     }  
  1370.   
  1371.     /** 
  1372.      * get 請求 
  1373.      *  
  1374.      * @param url路徑 
  1375.      * @return 
  1376.      * @throws Exception 
  1377.      * @throws ClientProtocolException 
  1378.      */  
  1379.     public static HttpResponse get(String url) throws Exception {  
  1380.         HttpResponse response = null;  
  1381.         HttpClient client = new DefaultHttpClient();  
  1382.         // 設置鏈接超時  
  1383.         client.getParams().setIntParameter(  
  1384.                 HttpConnectionParams.CONNECTION_TIMEOUT, 10000);  
  1385.         // 設置編碼  
  1386.         // client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,  
  1387.         // "gb2312");  
  1388.         // get方式  
  1389.         HttpGet httpRequest = new HttpGet(url);  
  1390.         // 發出一個request,並返回一個基於http協議的response  
  1391.         // System.out.println("------toolkit 1066----------");  
  1392.         response = client.execute(httpRequest);  
  1393.         return response;  
  1394.     }  
  1395.   
  1396.     /** 
  1397.      * post請求 
  1398.      *  
  1399.      * @param path 
  1400.      *            請求的地址 
  1401.      * @param params 
  1402.      *            參數列表 
  1403.      * @return 
  1404.      * @throws Exception 
  1405.      */  
  1406.     public static InputStream postRequest(String path,  
  1407.             Map<String, String> params) throws Exception {  
  1408.         // 封裝請求參數  
  1409.         List<NameValuePair> pair = new ArrayList<NameValuePair>();  
  1410.         if (params != null && !params.isEmpty()) {  
  1411.             for (Map.Entry<String, String> entry : params.entrySet()) {  
  1412.                 pair.add(new BasicNameValuePair(entry.getKey(), entry  
  1413.                         .getValue()));  
  1414.             }  
  1415.         }  
  1416.         // 把請求參數變成請求體部分  
  1417.         UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");          
  1418.           
  1419.           
  1420.         // 使用HttpPost對象設置發送的URL路徑  
  1421.         final HttpPost post = new HttpPost(path);  
  1422.         // 發送請求體  
  1423.         post.setEntity(uee);  
  1424.         // 建立一個瀏覽器對象,以把POST對象向服務器發送,並返回響應消息  
  1425.         DefaultHttpClient dhc = new DefaultHttpClient();  
  1426.         // 設置鏈接超時  
  1427.         dhc.getParams().setIntParameter(  
  1428.                 HttpConnectionParams.CONNECTION_TIMEOUT, 10000);  
  1429.         dhc.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000); // 設置等待數據超時10s  
  1430.         HttpResponse response = dhc.execute(post);  
  1431.         Log.e("TAG""服務器返回狀態:----" + response.getStatusLine().getStatusCode());  
  1432.         if (response != null && response.getStatusLine().getStatusCode() == 200) {  
  1433.             return response.getEntity().getContent();  
  1434.         } else  
  1435.             post.abort();  
  1436.         return null;  
  1437.     }  
  1438.   
  1439.     /** 
  1440.      * post請求 
  1441.      *  
  1442.      * @param url路徑 
  1443.      * @param list 
  1444.      *            參數列表 
  1445.      * @return 
  1446.      * @throws IOException 
  1447.      * @throws ClientProtocolException 
  1448.      */  
  1449.     public static HttpResponse post(String url, List<BasicNameValuePair> list,  
  1450.             String encode) throws Throwable {  
  1451.         HttpResponse response = null;  
  1452.         HttpClient client = new DefaultHttpClient();  
  1453.         // 設置鏈接超時  
  1454.         client.getParams().setIntParameter(  
  1455.                 HttpConnectionParams.CONNECTION_TIMEOUT, 5000);  
  1456.         client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,  
  1457.                 5000); // 設置等待數據超時5s  
  1458.         // 建立一個 基於http協議的請求(post方式)  
  1459.         HttpPost httpRequest = new HttpPost(url);  
  1460.         if (list != null) {  
  1461.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);  
  1462.             // 將請求中的參數信息放置到request中  
  1463.             httpRequest.setEntity(entity);  
  1464.         }  
  1465.         // 發出一個request,並返回一個基於http協議的response  
  1466.         response = client.execute(httpRequest);  
  1467.         return response;  
  1468.   
  1469.     }  
  1470.   
  1471.     /* 
  1472.      * 參數說明: uploadUrl: Servlet的url fileName: 上傳圖片的文件名(如: qq.png) fileUrl: 
  1473.      * 上傳文件在手機客戶端的完整路徑(如: /sdcard/qq.png) 
  1474.      */  
  1475.     public static InputStream upload(String uploadUrl, String fileName,  
  1476.             String fileUrl) throws Exception {  
  1477.         String end = "\r\n";  
  1478.         String twoHyphens = "--";  
  1479.         String boundary = "*****";  
  1480.         InputStream is = null;  
  1481.         URL url = new URL(uploadUrl);  
  1482.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  1483.         /* 容許Input、Output,不使用Cache */  
  1484.         conn.setDoInput(true);  
  1485.         conn.setDoOutput(true);  
  1486.         conn.setUseCaches(false);  
  1487.         /* 設置傳送的method=POST */  
  1488.         conn.setRequestMethod("POST");  
  1489.         /* setRequestProperty */  
  1490.         conn.setRequestProperty("Connection""Keep-Alive");  
  1491.         conn.setRequestProperty("Charset""UTF-8");  
  1492.         conn.setRequestProperty("Content-Type""multipart/form-data;boundary="  
  1493.                 + boundary);  
  1494.         // 將phone放置到請求的頭部  
  1495.   
  1496.         if (fileName != null && fileUrl != null) {  
  1497.             conn.setRequestProperty("picName", fileName);  
  1498.             /* 設置DataOutputStream */  
  1499.             DataOutputStream ds = new DataOutputStream(conn.getOutputStream());  
  1500.             ds.writeBytes(twoHyphens + boundary + end);  
  1501.             ds.writeBytes("Content-Disposition: form-data; "  
  1502.                     + "name=\"file1\";filename=\"" + fileName + "\"" + end);  
  1503.             ds.writeBytes(end);  
  1504.   
  1505.             /* 取得文件的FileInputStream */  
  1506.             FileInputStream fStream = new FileInputStream(fileUrl);  
  1507.             /* 設置每次寫入1024bytes */  
  1508.             int bufferSize = 1024;  
  1509.             byte[] buffer = new byte[bufferSize];  
  1510.   
  1511.             int length = -1;  
  1512.             /* 從文件讀取數據至緩衝區 */  
  1513.             while ((length = fStream.read(buffer)) != -1) {  
  1514.                 /* 將資料寫入DataOutputStream中 */  
  1515.                 ds.write(buffer, 0, length);  
  1516.             }  
  1517.             ds.writeBytes(end);  
  1518.             ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  
  1519.   
  1520.             /* close streams */  
  1521.             fStream.close();  
  1522.             ds.flush();  
  1523.             ds.close();  
  1524.         }  
  1525.         /* 取得Response內容 */  
  1526.         is = conn.getInputStream();  
  1527.         return is;  
  1528.     }  
  1529.   
  1530.     // -------------------------------------加密,驗證,轉換系列-----------------------------------------------------------  
  1531.     /** 
  1532.      * 驗證是否爲手機號碼 
  1533.      *  
  1534.      * @param mobiles 
  1535.      * @return 
  1536.      */  
  1537.     public static boolean isMobileNO(String mobiles) {  
  1538.         // Pattern p =  
  1539.         // Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,2,5-9]))\\d{8}$");  
  1540.         Pattern p = Pattern.compile("^([0-9]{3})\\d{8}$");  
  1541.         Matcher m = p.matcher(mobiles);  
  1542.         return m.matches();  
  1543.     }  
  1544.   
  1545.     /** 
  1546.      * 驗證輸入是否爲郵箱 
  1547.      *  
  1548.      * @param strEmail 
  1549.      * @return 
  1550.      */  
  1551.     public static boolean isEmail(String strEmail) {  
  1552.         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]$";  
  1553.         Pattern p = Pattern.compile(strPattern);  
  1554.         Matcher m = p.matcher(strEmail);  
  1555.         return m.matches();  
  1556.     }  
  1557.   
  1558.     /** 
  1559.      * 驗證輸入是否6位數字 
  1560.      *  
  1561.      * @param strEmail 
  1562.      * @return 
  1563.      */  
  1564.     public static boolean isCode(String strCode) {  
  1565.         String strPattern = "^[0-9]{6}";  
  1566.         Pattern p = Pattern.compile(strPattern);  
  1567.         Matcher m = p.matcher(strCode);  
  1568.         return m.matches();  
  1569.     }  
  1570.   
  1571.     /** 
  1572.      * 驗證輸入是否6位字符包含數字和字母,不包含特殊字符 
  1573.      *  
  1574.      * @param strEmail 
  1575.      * @return 
  1576.      */  
  1577.     public static boolean isCheckCode(String strCode) {  
  1578.         String strPattern = "^[0-9a-zA-Z]{6}";  
  1579.         Pattern p = Pattern.compile(strPattern);  
  1580.         Matcher m = p.matcher(strCode);  
  1581.         return m.matches();  
  1582.     }  
  1583.   
  1584.     /** 
  1585.      * 驗證輸入是否6到12位上字符包含數字和字母,包含特殊字符 
  1586.      *  
  1587.      * @param strEmail 
  1588.      * @return 
  1589.      */  
  1590.     public static boolean isPassCode(String strCode) {  
  1591.         String strPattern = "^[0-9a-zA-Z@*%#()><!_~]{6,12}";  
  1592.         Pattern p = Pattern.compile(strPattern);  
  1593.         Matcher m = p.matcher(strCode);  
  1594.         return m.matches();  
  1595.     }  
  1596.   
  1597.     /** 
  1598.      * 過濾url 
  1599.      *  
  1600.      * @param str 
  1601.      * @return 
  1602.      */  
  1603.     public static boolean isLegalUrlParameters(String str) {  
  1604.         String strPattern = "[&=\\s]+";  
  1605.         Pattern p = Pattern.compile(strPattern);  
  1606.         Matcher m = p.matcher(str);  
  1607.         return m.find();  
  1608.     }  
  1609.   
  1610.     /** 
  1611.      * 驗證ip 
  1612.      *  
  1613.      * @param text 
  1614.      * @return 
  1615.      */  
  1616.     public static boolean isIp(String text) {  
  1617.         if (text != null && text != "") {  
  1618.             // 定義正則表達式  
  1619.             String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."  
  1620.                     + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."  
  1621.                     + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."  
  1622.                     + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";  
  1623.             // 判斷ip地址是否與正則表達式匹配  
  1624.             if (text.matches(regex)) {  
  1625.                 // 返回判斷信息  
  1626.                 return true;  
  1627.             } else {  
  1628.                 return false;  
  1629.             }  
  1630.         }  
  1631.         return false;  
  1632.     }  
  1633.   
  1634.     /** 
  1635.      * md5加密 
  1636.      *  
  1637.      * @param s 
  1638.      * @return 
  1639.      * @throws Exception 
  1640.      */  
  1641.     public final static String MD5(String s) throws Exception {  
  1642.         char hexDigits[] = { '0''1''2''3''4''5''6''7''8''9',  
  1643.                 'a''b''c''d''e''f' };  
  1644.   
  1645.         byte[] strTemp = s.getBytes();  
  1646.         MessageDigest mdTemp = MessageDigest.getInstance("MD5");  
  1647.         mdTemp.update(strTemp);  
  1648.         byte[] md = mdTemp.digest();  
  1649.         int j = md.length;  
  1650.         char str[] = new char[j * 2];  
  1651.         int k = 0;  
  1652.         for (int i = 0; i < j; i++) {  
  1653.             byte byte0 = md[i];  
  1654.             str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  1655.             str[k++] = hexDigits[byte0 & 0xf];  
  1656.         }  
  1657.         return new String(str);  
  1658.     }  
  1659.   
  1660.     /** 
  1661.      * 加密 
  1662.      *  
  1663.      * @param sSrc 
  1664.      *            原文 
  1665.      * @param sKey 
  1666.      *            密碼是16位 
  1667.      * @return 
  1668.      * @throws Exception 
  1669.      */  
  1670.     public static String AESEncrypt(String sSrc, String sKey) throws Exception {  
  1671.         if (sKey == null) {  
  1672.             System.out.print("Key爲空null");  
  1673.             return null;  
  1674.         }  
  1675.         // 判斷Key是否爲16位  
  1676.         if (sKey.length() != 16) {  
  1677.             System.out.print("Key無效");  
  1678.             return null;  
  1679.         }  
  1680.         byte[] raw = sKey.getBytes();  
  1681.         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
  1682.         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
  1683.         IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());  
  1684.         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);  
  1685.         byte[] encrypted = cipher.doFinal(sSrc.getBytes());  
  1686.         return byte2hex(encrypted).toLowerCase();  
  1687.     }  
  1688.   
  1689.     /** 
  1690.      * 解密 
  1691.      *  
  1692.      * @param sSrc 
  1693.      * @param sKey密碼是16位 
  1694.      * @return 
  1695.      * @throws Exception 
  1696.      */  
  1697.     public static String AESDecrypt(String sSrc, String sKey) throws Exception {  
  1698.         // 判斷Key是否正確  
  1699.         if (sKey == null) {  
  1700.             System.out.print("Key爲空null");  
  1701.             return null;  
  1702.         }  
  1703.         // 判斷Key是否爲16位  
  1704.         if (sKey.length() != 16) {  
  1705.             System.out.print("Key無效");  
  1706.             return null;  
  1707.         }  
  1708.         byte[] raw = sKey.getBytes("ASCII");  
  1709.         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
  1710.         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
  1711.         IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());  
  1712.         cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);  
  1713.         byte[] encrypted1 = hex2byte(sSrc);  
  1714.         byte[] original = cipher.doFinal(encrypted1);  
  1715.         String originalString = new String(original);  
  1716.         return originalString;  
  1717.     }  
  1718.   
  1719.     private static final byte[] HEX_CHAR_TABLE = { (byte'0', (byte'1',  
  1720.             (byte'2', (byte'3', (byte'4', (byte'5', (byte'6',  
  1721.             (byte'7', (byte'8', (byte'9', (byte'A', (byte'B',  
  1722.             (byte'C', (byte'D', (byte'E', (byte'F' };  
  1723.   
  1724.     /** 
  1725.      * 十六進制無符號整數形式 
  1726.      *  
  1727.      * @param raw 
  1728.      * @param len 
  1729.      * @return 
  1730.      */  
  1731.     public static String getHex(byte[] raw, int len) {  
  1732.         byte[] hex = new byte[2 * len];  
  1733.         int index = 0;  
  1734.         int pos = 0;  
  1735.   
  1736.         for (byte b : raw) {  
  1737.             if (pos >= len)  
  1738.                 break;  
  1739.   
  1740.             pos++;  
  1741.             int v = b & 0xFF;  
  1742.             hex[index++] = HEX_CHAR_TABLE[v >>> 4];  
  1743.             hex[index++] = HEX_CHAR_TABLE[v & 0xF];  
  1744.         }  
  1745.         return new String(hex);  
  1746.     }  
  1747.   
  1748.     /** 
  1749.      * 轉換爲10進制無符號字符串 
  1750.      *  
  1751.      * @param bytes 
  1752.      * @return 
  1753.      */  
  1754.     public static long getDec(byte[] bytes) {  
  1755.         long result = 0;  
  1756.         long factor = 1;  
  1757.         for (int i = 0; i < bytes.length; ++i) {  
  1758.             long value = bytes[i] & 0xffl;  
  1759.             result += value * factor;  
  1760.             factor *= 256l;  
  1761.         }  
  1762.         return result;  
  1763.     }  
  1764.   
  1765.     /** 
  1766.      * 二進制轉換爲16進制 
  1767.      *  
  1768.      * @param b 
  1769.      * @return 
  1770.      */  
  1771.     public static String byte2hex(byte[] b) {  
  1772.         String hs = "";  
  1773.         String stmp = "";  
  1774.         for (int n = 0; n < b.length; n++) {  
  1775.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
  1776.             if (stmp.length() == 1) {  
  1777.                 hs = hs + "0" + stmp;  
  1778.             } else {  
  1779.                 hs = hs + stmp;  
  1780.             }  
  1781.         }  
  1782.         return hs.toUpperCase();  
  1783.     }  
  1784.   
  1785.     /** 
  1786.      * 16進制轉換爲二進制 
  1787.      *  
  1788.      * @param strhex 
  1789.      * @return 
  1790.      */  
  1791.     public static byte[] hex2byte(String strhex) {  
  1792.         if (strhex == null) {  
  1793.             return null;  
  1794.         }  
  1795.         int l = strhex.length();  
  1796.         if (l % 2 == 1) {  
  1797.             return null;  
  1798.         }  
  1799.         byte[] b = new byte[l / 2];  
  1800.         for (int i = 0; i != l / 2; i++) {  
  1801.             b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),  
  1802.                     16);  
  1803.         }  
  1804.         return b;  
  1805.     }  
  1806.   
  1807.     /** 
  1808.      * 16進制字符轉換爲int 
  1809.      *  
  1810.      * @param c 
  1811.      * @return 
  1812.      */  
  1813.     public static int reverseToInt(char c) {  
  1814.         if (c == 'A')  
  1815.             return 10;  
  1816.         else if (c == 'B')  
  1817.             return 11;  
  1818.         else if (c == 'C')  
  1819.             return 12;  
  1820.         else if (c == 'D')  
  1821.             return 13;  
  1822.         else if (c == 'E')  
  1823.             return 14;  
  1824.         else if (c == 'F')  
相關文章
相關標籤/搜索