分享

Android 最常用的快速开发工具类

 gearss 2016-05-21

先保存下载,以备之需。

      Android开发的工具类能很好的封装一些常用的操作,以后使用起来也非常方便,我把我经常使用的工具类分享给大家。

FileCache:

[java] view plaincopy
  1. package com.pztuan.common.util;  
  2.   
  3. import java.io.File;  
  4. import android.content.Context;  
  5.   
  6. public class FileCache {  
  7.     private File cacheDir;  
  8.   
  9.     public FileCache(Context context) {  
  10.         // 判断外存SD卡挂载状态,如果挂载正常,创建SD卡缓存文件夹  
  11.         if (android.os.Environment.getExternalStorageState().equals(  
  12.                 android.os.Environment.MEDIA_MOUNTED)) {  
  13.             cacheDir = new File(  
  14.                     android.os.Environment.getExternalStorageDirectory(),  
  15.                     "PztCacheDir");  
  16.         } else {  
  17.             // SD卡挂载不正常,获取本地缓存文件夹(应用包所在目录)  
  18.             cacheDir = context.getCacheDir();  
  19.         }  
  20.         if (!cacheDir.exists()) {  
  21.             cacheDir.mkdirs();  
  22.         }  
  23.     }  
  24.   
  25.     public File getFile(String url) {  
  26.         String fileName = String.valueOf(url.hashCode());  
  27.         File file = new File(cacheDir, fileName);  
  28.         return file;  
  29.     }  
  30.   
  31.     public void clear() {  
  32.         File[] files = cacheDir.listFiles();  
  33.         for (File f : files)  
  34.             f.delete();  
  35.     }  
  36.   
  37.     public String getCacheSize() {  
  38.         long size = 0;  
  39.         if (cacheDir.exists()) {  
  40.             File[] files = cacheDir.listFiles();  
  41.             for (File f : files) {  
  42.                 size += f.length();  
  43.             }  
  44.         }  
  45.         String cacheSize = String.valueOf(size / 1024 / 1024) + "M";  
  46.         return cacheSize;  
  47.     }  
  48.   
  49. }  

NetWorkUtil(网络类):

[java] view plaincopy
  1. package com.pztuan.common.util;  
  2.   
  3. import android.content.Context;  
  4. import android.net.ConnectivityManager;  
  5. import android.net.NetworkInfo;  
  6. import android.net.NetworkInfo.State;  
  7. import android.net.wifi.WifiManager;  
  8.   
  9. import java.security.MessageDigest;  
  10.   
  11. /** 
  12.  *  
  13.  * @author suncat 
  14.  * @category 网络工具 
  15.  */  
  16. public class NetWorkUtil {  
  17.     private final static String[] hexDigits = { "0""1""2""3""4""5",  
  18.             "6""7""8""9""a""b""c""d""e""f" };  
  19.     public static final int STATE_DISCONNECT = 0;  
  20.     public static final int STATE_WIFI = 1;  
  21.     public static final int STATE_MOBILE = 2;  
  22.   
  23.     public static String concatUrlParams() {  
  24.   
  25.         return null;  
  26.     }  
  27.   
  28.     public static String encodeUrl() {  
  29.   
  30.         return null;  
  31.     }  
  32.   
  33.     public static boolean isNetWorkConnected(Context context) {  
  34.         ConnectivityManager cm = (ConnectivityManager) context  
  35.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  36.         NetworkInfo[] nis = cm.getAllNetworkInfo();  
  37.         if (nis != null) {  
  38.             for (NetworkInfo ni : nis) {  
  39.                 if (ni != null) {  
  40.                     if (ni.isConnected()) {  
  41.                         return true;  
  42.                     }  
  43.                 }  
  44.             }  
  45.         }  
  46.   
  47.         return false;  
  48.     }  
  49.   
  50.     public static boolean isWifiConnected(Context context) {  
  51.         WifiManager wifiMgr = (WifiManager) context  
  52.                 .getSystemService(Context.WIFI_SERVICE);  
  53.         boolean isWifiEnable = wifiMgr.isWifiEnabled();  
  54.   
  55.         return isWifiEnable;  
  56.     }  
  57.   
  58.     public static boolean isNetworkAvailable(Context context) {  
  59.         ConnectivityManager cm = (ConnectivityManager) context  
  60.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  61.         NetworkInfo networkInfo = cm.getActiveNetworkInfo();  
  62.         if (networkInfo != null) {  
  63.             return networkInfo.isAvailable();  
  64.         }  
  65.   
  66.         return false;  
  67.     }  
  68.   
  69.     private static String byteArrayToHexString(byte[] b) {  
  70.         StringBuffer resultSb = new StringBuffer();  
  71.         for (int i = 0; i < b.length; i++) {  
  72.             resultSb.append(byteToHexString(b[i]));  
  73.         }  
  74.         return resultSb.toString();  
  75.     }  
  76.   
  77.     private static String byteToHexString(byte b) {  
  78.         int n = b;  
  79.         if (n < 0)  
  80.             n = 256 + n;  
  81.         int d1 = n / 16;  
  82.         int d2 = n % 16;  
  83.         return hexDigits[d1] + hexDigits[d2];  
  84.     }  
  85.   
  86.     public static String md5Encode(String origin) {  
  87.         String resultString = null;  
  88.   
  89.         try {  
  90.             resultString = new String(origin);  
  91.             MessageDigest md = MessageDigest.getInstance("MD5");  
  92.             resultString = new String(md.digest(resultString.getBytes()));  
  93.         } catch (Exception ex) {  
  94.             ex.printStackTrace();  
  95.         }  
  96.   
  97.         return resultString;  
  98.     }  
  99.   
  100.     public static String md5EncodeToHexString(String origin) {  
  101.         String resultString = null;  
  102.   
  103.         try {  
  104.             resultString = new String(origin);  
  105.             MessageDigest md = MessageDigest.getInstance("MD5");  
  106.             resultString = byteArrayToHexString(md.digest(resultString  
  107.                     .getBytes()));  
  108.         } catch (Exception ex) {  
  109.             ex.printStackTrace();  
  110.         }  
  111.   
  112.         return resultString;  
  113.     }  
  114.   
  115.     public static int getNetworkState(Context context) {  
  116.         ConnectivityManager connManager = (ConnectivityManager) context  
  117.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  118.   
  119.         // Wifi  
  120.         State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)  
  121.                 .getState();  
  122.         if (state == State.CONNECTED || state == State.CONNECTING) {  
  123.             return STATE_WIFI;  
  124.         }  
  125.   
  126.         // 3G  
  127.         state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)  
  128.                 .getState();  
  129.         if (state == State.CONNECTED || state == State.CONNECTING) {  
  130.             return STATE_MOBILE;  
  131.         }  
  132.         return STATE_DISCONNECT;  
  133.     }  
  134. }  

Tools(常用小功能:号码正则匹配、日期计算、获取imei号、计算listview高度):


[java] view plaincopy
  1. package com.pztuan.common.util;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.text.ParseException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7. import java.util.regex.Matcher;  
  8. import java.util.regex.Pattern;  
  9.   
  10. import android.annotation.SuppressLint;  
  11. import android.content.Context;  
  12. import android.os.Environment;  
  13. import android.telephony.TelephonyManager;  
  14. import android.view.View;  
  15. import android.view.ViewGroup;  
  16. import android.widget.ListAdapter;  
  17. import android.widget.ListView;  
  18. import android.widget.Toast;  
  19.   
  20. @SuppressLint("DefaultLocale")  
  21. public class Tools {  
  22.   
  23.     private final static String[] hexDigits = { "0""1""2""3""4""5",  
  24.             "6""7""8""9""a""b""c""d""e""f" };  
  25.   
  26.     public static String byteArrayToHexString(byte[] b) {  
  27.         StringBuffer resultSb = new StringBuffer();  
  28.         for (int i = 0; i < b.length; i++) {  
  29.             resultSb.append(byteToHexString(b[i]));  
  30.         }  
  31.         return resultSb.toString();  
  32.     }  
  33.   
  34.     private static String byteToHexString(byte b) {  
  35.         int n = b;  
  36.         if (n < 0)  
  37.             n = 256 + n;  
  38.         int d1 = n / 16;  
  39.         int d2 = n % 16;  
  40.         return hexDigits[d1] + hexDigits[d2];  
  41.     }  
  42.   
  43.     /** 
  44.      * md5 加密 
  45.      *  
  46.      * @param origin 
  47.      * @return 
  48.      */  
  49.     public static String md5Encode(String origin) {  
  50.         String resultString = null;  
  51.         try {  
  52.             resultString = new String(origin);  
  53.             MessageDigest md = MessageDigest.getInstance("MD5");  
  54.             resultString = byteArrayToHexString(md.digest(resultString  
  55.                     .getBytes()));  
  56.         } catch (Exception ex) {  
  57.             ex.printStackTrace();  
  58.         }  
  59.         return resultString;  
  60.     }  
  61.   
  62.     /** 
  63.      * 手机号码格式匹配 
  64.      *  
  65.      * @param mobiles 
  66.      * @return 
  67.      */  
  68.     public static boolean isMobileNO(String mobiles) {  
  69.         Pattern p = Pattern  
  70.                 .compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,3,5-9]))\\d{8}$");  
  71.         Matcher m = p.matcher(mobiles);  
  72.         System.out.println(m.matches() + "-telnum-");  
  73.         return m.matches();  
  74.     }  
  75.   
  76.     /** 
  77.      * 是否含有指定字符 
  78.      *  
  79.      * @param expression 
  80.      * @param text 
  81.      * @return 
  82.      */  
  83.     private static boolean matchingText(String expression, String text) {  
  84.         Pattern p = Pattern.compile(expression);  
  85.         Matcher m = p.matcher(text);  
  86.         boolean b = m.matches();  
  87.         return b;  
  88.     }  
  89.   
  90.     /** 
  91.      * 邮政编码 
  92.      *  
  93.      * @param zipcode 
  94.      * @return 
  95.      */  
  96.     public static boolean isZipcode(String zipcode) {  
  97.         Pattern p = Pattern.compile("[0-9]\\d{5}");  
  98.         Matcher m = p.matcher(zipcode);  
  99.         System.out.println(m.matches() + "-zipcode-");  
  100.         return m.matches();  
  101.     }  
  102.   
  103.     /** 
  104.      * 邮件格式 
  105.      *  
  106.      * @param email 
  107.      * @return 
  108.      */  
  109.     public static boolean isValidEmail(String email) {  
  110.         Pattern p = Pattern  
  111.                 .compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");  
  112.         Matcher m = p.matcher(email);  
  113.         System.out.println(m.matches() + "-email-");  
  114.         return m.matches();  
  115.     }  
  116.   
  117.     /** 
  118.      * 固话号码格式 
  119.      *  
  120.      * @param telfix 
  121.      * @return 
  122.      */  
  123.     public static boolean isTelfix(String telfix) {  
  124.         Pattern p = Pattern.compile("d{3}-d{8}|d{4}-d{7}");  
  125.         Matcher m = p.matcher(telfix);  
  126.         System.out.println(m.matches() + "-telfix-");  
  127.         return m.matches();  
  128.     }  
  129.   
  130.     /** 
  131.      * 用户名匹配 
  132.      *  
  133.      * @param name 
  134.      * @return 
  135.      */  
  136.     public static boolean isCorrectUserName(String name) {  
  137.         Pattern p = Pattern.compile("([A-Za-z0-9]){2,10}");  
  138.         Matcher m = p.matcher(name);  
  139.         System.out.println(m.matches() + "-name-");  
  140.         return m.matches();  
  141.     }  
  142.   
  143.     /** 
  144.      * 密码匹配,以字母开头,长度 在6-18之间,只能包含字符、数字和下划线。 
  145.      *  
  146.      * @param pwd 
  147.      * @return 
  148.      *  
  149.      */  
  150.     public static boolean isCorrectUserPwd(String pwd) {  
  151.         Pattern p = Pattern.compile("\\w{6,18}");  
  152.         Matcher m = p.matcher(pwd);  
  153.         System.out.println(m.matches() + "-pwd-");  
  154.         return m.matches();  
  155.     }  
  156.   
  157.     /** 
  158.      * 检查是否存在SDCard 
  159.      *  
  160.      * @return 
  161.      */  
  162.     public static boolean hasSdcard() {  
  163.         String state = Environment.getExternalStorageState();  
  164.         if (state.equals(Environment.MEDIA_MOUNTED)) {  
  165.             return true;  
  166.         } else {  
  167.             return false;  
  168.         }  
  169.     }  
  170.   
  171.     /** 
  172.      * 计算剩余日期 
  173.      *  
  174.      * @param remainTime 
  175.      * @return 
  176.      */  
  177.     public static String calculationRemainTime(String endTime, long countDown) {  
  178.   
  179.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  180.         try {  
  181.             Date now = new Date(System.currentTimeMillis());// 获取当前时间  
  182.             Date endData = df.parse(endTime);  
  183.             long l = endData.getTime() - countDown - now.getTime();  
  184.             long day = l / (24 * 60 * 60 * 1000);  
  185.             long hour = (l / (60 * 60 * 1000) - day * 24);  
  186.             long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);  
  187.             long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);  
  188.             return "剩余" + day + "天" + hour + "小时" + min + "分" + s + "秒";  
  189.         } catch (ParseException e) {  
  190.             e.printStackTrace();  
  191.         }  
  192.         return "";  
  193.     }  
  194.   
  195.     public static void showLongToast(Context act, String pMsg) {  
  196.         Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_LONG);  
  197.         toast.show();  
  198.     }  
  199.   
  200.     public static void showShortToast(Context act, String pMsg) {  
  201.         Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_SHORT);  
  202.         toast.show();  
  203.     }  
  204.   
  205.     /** 
  206.      * 获取手机Imei号 
  207.      *  
  208.      * @param context 
  209.      * @return 
  210.      */  
  211.     public static String getImeiCode(Context context) {  
  212.         TelephonyManager tm = (TelephonyManager) context  
  213.                 .getSystemService(Context.TELEPHONY_SERVICE);  
  214.         return tm.getDeviceId();  
  215.     }  
  216.   
  217.     /** 
  218.      * @author sunglasses 
  219.      * @param listView 
  220.      * @category 计算listview的高度 
  221.      */  
  222.     public static void setListViewHeightBasedOnChildren(ListView listView) {  
  223.         ListAdapter listAdapter = listView.getAdapter();  
  224.         if (listAdapter == null) {  
  225.             // pre-condition  
  226.             return;  
  227.         }  
  228.   
  229.         int totalHeight = 0;  
  230.         for (int i = 0; i < listAdapter.getCount(); i++) {  
  231.             View listItem = listAdapter.getView(i, null, listView);  
  232.             listItem.measure(00);  
  233.             totalHeight += listItem.getMeasuredHeight();  
  234.         }  
  235.   
  236.         ViewGroup.LayoutParams params = listView.getLayoutParams();  
  237.         params.height = totalHeight  
  238.                 + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
  239.         listView.setLayoutParams(params);  
  240.     }  
  241. }  

SharedPreferencesUtil:

[java] view plaincopy
  1. package com.pztuan.db;  
  2.   
  3. import android.content.Context;  
  4. import android.content.SharedPreferences;  
  5. import android.content.SharedPreferences.Editor;  
  6. import android.util.Log;  
  7.   
  8. import java.util.ArrayList;  
  9. import java.util.Set;  
  10.   
  11. public class SharedPreferencesUtil {  
  12.     private static final String TAG = "PZTuan.SharePreferencesUtil";  
  13.     private static final String SHAREDPREFERENCE_NAME = "sharedpreferences_pztuan";  
  14.   
  15.     private static SharedPreferencesUtil mInstance;  
  16.   
  17.     private static SharedPreferences mSharedPreferences;  
  18.   
  19.     private static SharedPreferences.Editor mEditor;  
  20.   
  21.     public synchronized static SharedPreferencesUtil getInstance(Context context) {  
  22.         if (mInstance == null) {  
  23.             mInstance = new SharedPreferencesUtil(context);  
  24.         }  
  25.   
  26.         return mInstance;  
  27.     }  
  28.   
  29.     private SharedPreferencesUtil(Context context) {  
  30.         mSharedPreferences = context.getSharedPreferences(  
  31.                 SHAREDPREFERENCE_NAME, Context.MODE_PRIVATE);  
  32.         mEditor = mSharedPreferences.edit();  
  33.     }  
  34.   
  35.     public synchronized boolean putString(String key, String value) {  
  36.         mEditor.putString(key, value);  
  37.         return mEditor.commit();  
  38.     }  
  39.   
  40.     public synchronized boolean putStringArrayList(String key,  
  41.             ArrayList<String> value) {  
  42.   
  43.         for (int j = 0; j < value.size() - 1; j++) {  
  44.             if (value.get(value.size() - 1).equals(value.get(j))) {  
  45.                 value.remove(j);  
  46.             }  
  47.         }  
  48.         mEditor.putInt("citySize", value.size());  
  49.   
  50.         if (value.size() == 4) {  
  51.             mEditor.putString(key + 0, value.get(3));  
  52.             mEditor.putString(key + 1, value.get(0));  
  53.             mEditor.putString(key + 2, value.get(1));  
  54.         } else if (value.size() == 3) {  
  55.             mEditor.putString(key + 0, value.get(2));  
  56.             mEditor.putString(key + 1, value.get(0));  
  57.             mEditor.putString(key + 2, value.get(1));  
  58.         } else {  
  59.             for (int i = 0; i < value.size(); i++) {  
  60.                 mEditor.putString(key + i, value.get(value.size() - 1 - i));  
  61.             }  
  62.   
  63.         }  
  64.         return mEditor.commit();  
  65.     }  
  66.   
  67.     public synchronized boolean putInt(String key, int value) {  
  68.         mEditor.putInt(key, value);  
  69.         return mEditor.commit();  
  70.     }  
  71.   
  72.     public synchronized boolean putLong(String key, long value) {  
  73.         mEditor.putLong(key, value);  
  74.         return mEditor.commit();  
  75.     }  
  76.   
  77.     public synchronized boolean putFloat(String key, float value) {  
  78.         mEditor.putFloat(key, value);  
  79.         return mEditor.commit();  
  80.     }  
  81.   
  82.     public synchronized boolean putBoolean(String key, boolean value) {  
  83.         mEditor.putBoolean(key, value);  
  84.         return mEditor.commit();  
  85.     }  
  86.   
  87.     public synchronized boolean putStringSet(String key, Set<String> value) {  
  88.         mEditor.putStringSet(key, value);  
  89.         return mEditor.commit();  
  90.     }  
  91.   
  92.     public String getString(String key, String value) {  
  93.         return mSharedPreferences.getString(key, value);  
  94.     }  
  95.   
  96.     public ArrayList<String> getStringArrayList(String key, int size) {  
  97.         ArrayList<String> al = new ArrayList<String>();  
  98.         int loop;  
  99.         if (size > 4)  
  100.             loop = 4;  
  101.         else  
  102.             loop = size;  
  103.         for (int i = 0; i < loop; i++) {  
  104.             String name = mSharedPreferences.getString(key + i, null);  
  105.             al.add(name);  
  106.         }  
  107.         return al;  
  108.     }  
  109.   
  110.     public int getInt(String key, int value) {  
  111.         return mSharedPreferences.getInt(key, value);  
  112.     }  
  113.   
  114.     public long getLong(String key, long value) {  
  115.         return mSharedPreferences.getLong(key, value);  
  116.     }  
  117.   
  118.     public float getFloat(String key, float value) {  
  119.         return mSharedPreferences.getFloat(key, value);  
  120.     }  
  121.   
  122.     public boolean getBoolean(String key, boolean value) {  
  123.         return mSharedPreferences.getBoolean(key, value);  
  124.     }  
  125.   
  126.     public Set<String> getStringSet(String key, Set<String> value) {  
  127.         return mSharedPreferences.getStringSet(key, value);  
  128.     }  
  129.   
  130.     public boolean remove(String key) {  
  131.         mEditor.remove(key);  
  132.         return mEditor.commit();  
  133.     }  
  134.   
  135.     private static final String PREFERENCES_AUTO_LOGIN = "yyUserAutoLogin";  
  136.     private static final String PREFERENCES_USER_NAME = "yyUserName";  
  137.     private static final String PREFERENCES_USER_PASSWORD = "yyUserPassword";  
  138.   
  139.     public boolean isAutoLogin() {  
  140.         return mSharedPreferences.getBoolean(PREFERENCES_AUTO_LOGIN, false);  
  141.     }  
  142.   
  143.     public String getUserName() {  
  144.         return mSharedPreferences.getString(PREFERENCES_USER_NAME, "");  
  145.     }  
  146.   
  147.     public String getUserPwd() {  
  148.         return mSharedPreferences.getString(PREFERENCES_USER_PASSWORD, "");  
  149.     }  
  150.   
  151.     public void saveLoginInfo(Boolean autoLogin, String userName,  
  152.             String userPassword) {  
  153.         assert (mEditor != null);  
  154.         mEditor.putBoolean(PREFERENCES_AUTO_LOGIN, autoLogin);  
  155.         mEditor.putString(PREFERENCES_USER_NAME, userName);  
  156.         mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);  
  157.         mEditor.commit();  
  158.     }  
  159.   
  160.     public void saveLoginPassword(String userPassword) {  
  161.         mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);  
  162.         mEditor.commit();  
  163.     }  
  164.   
  165.     public void saveLoginUserid(String userid) {  
  166.         mEditor.putString("userid", userid);  
  167.         mEditor.commit();  
  168.     }  
  169.   
  170.     public void clearUserInfo() {  
  171.         assert (mEditor != null);  
  172.         mEditor.putBoolean(PREFERENCES_AUTO_LOGIN, false);  
  173.         mEditor.putString(PREFERENCES_USER_NAME, "");  
  174.         mEditor.putString(PREFERENCES_USER_PASSWORD, "");  
  175.         mEditor.putString("userid""");  
  176.         mEditor.commit();  
  177.     }  
  178.   
  179. }  

转载自:http://blog.csdn.net/rain_butterfly/article/details/39525601

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多