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')  
  1825.             return 15;  
  1826.         else  
  1827.             return Integer.parseInt(String.valueOf(c));  
  1828.     }  
  1829.   
  1830.     /** 
  1831.      * 16进制加法 
  1832.      *  
  1833.      * @param src1 
  1834.      * @param src2 
  1835.      * @return 
  1836.      */  
  1837.     public static String hexAdd(String src1, String src2) {  
  1838.         int length1 = src1.toUpperCase().length();  
  1839.         int length2 = src2.toUpperCase().length();  
  1840.         String extend = "";  
  1841.         char sum[] = null;  
  1842.         if (length1 > length2) {// 如果src1的长度大于src2  
  1843.             int num = length1 - length2;  
  1844.             sum = new char[length1];  
  1845.             String zero = "";  
  1846.             for (int i = 0; i < num; i++) {  
  1847.                 zero += "0";  
  1848.             }  
  1849.             src2 = zero + src2;  
  1850.             // 遍历数组,然后相加  
  1851.             int add = 0, rest = 0;  
  1852.             for (int i = length1 - 1; i >= 0; i--) {  
  1853.                 int a = reverseToInt(src1.toUpperCase().charAt(i));  
  1854.                 int b = reverseToInt(src2.toUpperCase().charAt(i));  
  1855.                 if (a + b + add >= 16) {  
  1856.                     int temp = add;  
  1857.                     add = (a + b + add) / 16;  
  1858.                     rest = (a + b + temp) % 16;  
  1859.                     sum[i] = reverseToChar(rest);  
  1860.                 } else {  
  1861.                     sum[i] = reverseToChar(a + b + add);  
  1862.                     add = 0;  
  1863.                 }  
  1864.             }  
  1865.         } else if (length1 < length2) {// src1的长度小于src2  
  1866.             int num = length2 - length1;  
  1867.             sum = new char[length2];  
  1868.             String zero = "";  
  1869.             for (int i = 0; i < num; i++) {  
  1870.                 zero += "0";  
  1871.             }  
  1872.             src1 = zero + src1;  
  1873.             // 遍历数组,然后相加  
  1874.             int add = 0, rest = 0;  
  1875.             for (int i = length2 - 1; i >= 0; i--) {  
  1876.                 int a = reverseToInt(src1.toUpperCase().charAt(i));  
  1877.                 int b = reverseToInt(src2.toUpperCase().charAt(i));  
  1878.                 if (a + b + add >= 16) {  
  1879.                     int temp = add;  
  1880.                     add = (a + b + add) / 16;  
  1881.                     rest = (a + b + temp) % 16;  
  1882.                     sum[i] = reverseToChar(rest);  
  1883.                 } else {  
  1884.                     sum[i] = reverseToChar(a + b + add);  
  1885.                     add = 0;  
  1886.                 }  
  1887.             }  
  1888.         } else {// 如果相等  
  1889.             // 遍历数组,然后相加  
  1890.             sum = new char[length2];  
  1891.             int add = 0, rest = 0;  
  1892.             for (int i = length2 - 1; i >= 0; i--) {  
  1893.                 int a = reverseToInt(src1.toUpperCase().charAt(i));  
  1894.                 int b = reverseToInt(src2.toUpperCase().charAt(i));  
  1895.                 if (a + b + add >= 16) {  
  1896.                     int temp = add;  
  1897.                     add = (a + b + add) / 16;  
  1898.                     rest = (a + b + temp) % 16;  
  1899.                     sum[i] = reverseToChar(rest);  
  1900.                     if (i == 0) {// 如果i==0  
  1901.                         extend = String.valueOf(add);  
  1902.                     }  
  1903.                 } else {  
  1904.                     sum[i] = reverseToChar(a + b + add);  
  1905.                     add = 0;  
  1906.                 }  
  1907.             }  
  1908.         }  
  1909.         return extend + String.valueOf(sum);  
  1910.     }  
  1911.   
  1912.     /** 
  1913.      * 整形转为16进制表示的char 
  1914.      *  
  1915.      * @param num 
  1916.      * @return 
  1917.      */  
  1918.     public static char reverseToChar(int num) {  
  1919.         /* 
  1920.          * if (num == 10) return 'A'; else if (num == 11) return 'B'; else if 
  1921.          * (num == 12) return 'C'; else if (num == 13) return 'D'; else if (num 
  1922.          * == 14) return 'E'; else if (num == 15) return 'F'; else return 
  1923.          * String.valueOf(num).charAt(0); 
  1924.          */  
  1925.         return Integer.toHexString(num).charAt(0);  
  1926.     }  
  1927.   
  1928.     /** 
  1929.      * 16进制字符按位取反 
  1930.      *  
  1931.      * @param num 
  1932.      * @return 
  1933.      */  
  1934.     public static String revers(String num) {  
  1935.         num = num.toUpperCase();  
  1936.         char array[] = num.toCharArray();  
  1937.         for (int i = 0; i < array.length; i++) {  
  1938.             if (array[i] == 'A')  
  1939.                 array[i] = reverseToChar(15 - 10);  
  1940.             else if (array[i] == 'B')  
  1941.                 array[i] = reverseToChar(15 - 11);  
  1942.             else if (array[i] == 'C')  
  1943.                 array[i] = reverseToChar(15 - 12);  
  1944.             else if (array[i] == 'D')  
  1945.                 array[i] = reverseToChar(15 - 13);  
  1946.             else if (array[i] == 'E')  
  1947.                 array[i] = reverseToChar(15 - 14);  
  1948.             else if (array[i] == 'F')  
  1949.                 array[i] = reverseToChar(15 - 15);  
  1950.             else  
  1951.                 array[i] = reverseToChar(15 - Integer.parseInt(String  
  1952.                         .valueOf(array[i])));  
  1953.         }  
  1954.         //  
  1955.         return String.valueOf(array);  
  1956.     }  
  1957.   
  1958.     /** 
  1959.      * 输入流转换为byte数组 
  1960.      *  
  1961.      * @param is 
  1962.      * @return 
  1963.      * @throws IOException 
  1964.      */  
  1965.     public static byte[] streamToBytes(InputStream is) throws IOException {  
  1966.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  1967.         byte[] buffer = new byte[1024];  
  1968.   
  1969.         int len;  
  1970.         while ((len = is.read(buffer)) != -1) {  
  1971.             os.write(buffer, 0, len);  
  1972.         }  
  1973.         return os.toByteArray();  
  1974.     }  
  1975.   
  1976.     /** 
  1977.      * 将输入流转为字符串 
  1978.      *  
  1979.      * @param is 
  1980.      *            输入流 
  1981.      * @param encode 
  1982.      *            编码方式 
  1983.      * @return 
  1984.      * @throws Exception 
  1985.      */  
  1986.     public static String streamToString(InputStream is, String encode)  
  1987.             throws Exception {  
  1988.   
  1989.         byte[] data = streamToBytes(is);  
  1990.         return new String(data, encode);  
  1991.     }  
  1992.   
  1993.     /** 
  1994.      * 将String转换成InputStream 
  1995.      *  
  1996.      * @param in 
  1997.      * @return 
  1998.      * @throws UnsupportedEncodingException 
  1999.      * @throws Exception 
  2000.      */  
  2001.     public static InputStream StringTOInputStream(String in, String encode)  
  2002.             throws IOException {  
  2003.         ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes(encode));  
  2004.         return is;  
  2005.     }  
  2006.   
  2007.     /** 
  2008.      * 将byte数组转换为输入流 
  2009.      *  
  2010.      * @param data 
  2011.      * @return 
  2012.      */  
  2013.     public static InputStream ByteToStream(byte[] data) {  
  2014.         ByteArrayInputStream os = new ByteArrayInputStream(data);  
  2015.         return os;  
  2016.     }  
  2017.   
  2018.     /** 
  2019.      * 资源文件转换为bitmap 
  2020.      *  
  2021.      * @param context 
  2022.      * @param resId 
  2023.      * @return 
  2024.      */  
  2025.     public static Bitmap getBitmapFromResource(Context context, int resId) {  
  2026.         InputStream is = context.getResources().openRawResource(resId);  
  2027.         return BitmapFactory.decodeStream(is);  
  2028.     }  
  2029.   
  2030.     /** 
  2031.      * 返回当前日期xxxx年x月xx日x星期 
  2032.      *  
  2033.      * @return 
  2034.      */  
  2035.     public static String getDate() {  
  2036.         Date date = new Date();  
  2037.         Calendar c = Calendar.getInstance();  
  2038.         c.setTime(date);  
  2039.         String[] weekDays = { "星期日""星期一""星期二""星期三""星期四""星期五""星期六" };  
  2040.         int w = c.get(Calendar.DAY_OF_WEEK) - 1;  
  2041.         if (w < 0) {  
  2042.             w = 0;  
  2043.         }  
  2044.         String mDate = c.get(Calendar.YEAR) + "年" + c.get(Calendar.MONTH) + "月"  
  2045.                 + c.get(Calendar.DATE) + "日  " + weekDays[w];  
  2046.         return mDate;  
  2047.     }  
  2048. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值