本文出自【张鸿洋的博客】并 做了部分修改。

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311

打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~

在此感谢群里给我发项目中工具类的兄弟/姐妹~

1、日志工具类L.java

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.util.Log;
  3. /**
  4. * Log统一管理类
  5. *
  6. *
  7. *
  8. */
  9. public class L
  10. {
  11. private L()
  12. {
  13. /* cannot be instantiated */
  14. throw new UnsupportedOperationException("cannot be instantiated");
  15. }
  16. public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
  17. private static final String TAG = "way";
  18. // 下面四个是默认tag的函数
  19. public static void i(String msg)
  20. {
  21. if (isDebug)
  22. Log.i(TAG, msg);
  23. }
  24. public static void d(String msg)
  25. {
  26. if (isDebug)
  27. Log.d(TAG, msg);
  28. }
  29. public static void e(String msg)
  30. {
  31. if (isDebug)
  32. Log.e(TAG, msg);
  33. }
  34. public static void v(String msg)
  35. {
  36. if (isDebug)
  37. Log.v(TAG, msg);
  38. }
  39. // 下面是传入自定义tag的函数
  40. public static void i(String tag, String msg)
  41. {
  42. if (isDebug)
  43. Log.i(tag, msg);
  44. }
  45. public static void d(String tag, String msg)
  46. {
  47. if (isDebug)
  48. Log.i(tag, msg);
  49. }
  50. public static void e(String tag, String msg)
  51. {
  52. if (isDebug)
  53. Log.i(tag, msg);
  54. }
  55. public static void v(String tag, String msg)
  56. {
  57. if (isDebug)
  58. Log.i(tag, msg);
  59. }
  60. }

网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~

2、Toast统一管理类

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.content.Context;
  3. import android.widget.Toast;
  4. /**
  5. * Toast统一管理类
  6. *
  7. */
  8. public class T
  9. {
  10. private T()
  11. {
  12. /* cannot be instantiated */
  13. throw new UnsupportedOperationException("cannot be instantiated");
  14. }
  15. public static boolean isShow = true;
  16. /**
  17. * 短时间显示Toast
  18. *
  19. * @param context
  20. * @param message
  21. */
  22. public static void showShort(Context context, CharSequence message)
  23. {
  24. if (isShow)
  25. Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  26. }
  27. /**
  28. * 短时间显示Toast
  29. *
  30. * @param context
  31. * @param message
  32. */
  33. public static void showShort(Context context, int message)
  34. {
  35. if (isShow)
  36. Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  37. }
  38. /**
  39. * 长时间显示Toast
  40. *
  41. * @param context
  42. * @param message
  43. */
  44. public static void showLong(Context context, CharSequence message)
  45. {
  46. if (isShow)
  47. Toast.makeText(context, message, Toast.LENGTH_LONG).show();
  48. }
  49. /**
  50. * 长时间显示Toast
  51. *
  52. * @param context
  53. * @param message
  54. */
  55. public static void showLong(Context context, int message)
  56. {
  57. if (isShow)
  58. Toast.makeText(context, message, Toast.LENGTH_LONG).show();
  59. }
  60. /**
  61. * 自定义显示Toast时间
  62. *
  63. * @param context
  64. * @param message
  65. * @param duration
  66. */
  67. public static void show(Context context, CharSequence message, int duration)
  68. {
  69. if (isShow)
  70. Toast.makeText(context, message, duration).show();
  71. }
  72. /**
  73. * 自定义显示Toast时间
  74. *
  75. * @param context
  76. * @param message
  77. * @param duration
  78. */
  79. public static void show(Context context, int message, int duration)
  80. {
  81. if (isShow)
  82. Toast.makeText(context, message, duration).show();
  83. }
  84. }

也是非常简单的一个封装,能省则省了~~

3、SharedPreferences封装类SPUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.util.Map;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. public class SPUtils
  8. {
  9. /**
  10. * 保存在手机里面的文件名
  11. */
  12. public static final String FILE_NAME = "share_data";
  13. /**
  14. * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
  15. *
  16. * @param context
  17. * @param key
  18. * @param object
  19. */
  20. public static void put(Context context, String key, Object object)
  21. {
  22. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  23. Context.MODE_PRIVATE);
  24. SharedPreferences.Editor editor = sp.edit();
  25. if (object instanceof String)
  26. {
  27. editor.putString(key, (String) object);
  28. } else if (object instanceof Integer)
  29. {
  30. editor.putInt(key, (Integer) object);
  31. } else if (object instanceof Boolean)
  32. {
  33. editor.putBoolean(key, (Boolean) object);
  34. } else if (object instanceof Float)
  35. {
  36. editor.putFloat(key, (Float) object);
  37. } else if (object instanceof Long)
  38. {
  39. editor.putLong(key, (Long) object);
  40. } else
  41. {
  42. editor.putString(key, object.toString());
  43. }
  44. SharedPreferencesCompat.apply(editor);
  45. }
  46. /**
  47. * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
  48. *
  49. * @param context
  50. * @param key
  51. * @param defaultObject
  52. * @return
  53. */
  54. public static Object get(Context context, String key, Object defaultObject)
  55. {
  56. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  57. Context.MODE_PRIVATE);
  58. if (defaultObject instanceof String)
  59. {
  60. return sp.getString(key, (String) defaultObject);
  61. } else if (defaultObject instanceof Integer)
  62. {
  63. return sp.getInt(key, (Integer) defaultObject);
  64. } else if (defaultObject instanceof Boolean)
  65. {
  66. return sp.getBoolean(key, (Boolean) defaultObject);
  67. } else if (defaultObject instanceof Float)
  68. {
  69. return sp.getFloat(key, (Float) defaultObject);
  70. } else if (defaultObject instanceof Long)
  71. {
  72. return sp.getLong(key, (Long) defaultObject);
  73. }
  74. return null;
  75. }
  76. /**
  77. * 移除某个key值已经对应的值
  78. * @param context
  79. * @param key
  80. */
  81. public static void remove(Context context, String key)
  82. {
  83. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  84. Context.MODE_PRIVATE);
  85. SharedPreferences.Editor editor = sp.edit();
  86. editor.remove(key);
  87. SharedPreferencesCompat.apply(editor);
  88. }
  89. /**
  90. * 清除所有数据
  91. * @param context
  92. */
  93. public static void clear(Context context)
  94. {
  95. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  96. Context.MODE_PRIVATE);
  97. SharedPreferences.Editor editor = sp.edit();
  98. editor.clear();
  99. SharedPreferencesCompat.apply(editor);
  100. }
  101. /**
  102. * 查询某个key是否已经存在
  103. * @param context
  104. * @param key
  105. * @return
  106. */
  107. public static boolean contains(Context context, String key)
  108. {
  109. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  110. Context.MODE_PRIVATE);
  111. return sp.contains(key);
  112. }
  113. /**
  114. * 返回所有的键值对
  115. *
  116. * @param context
  117. * @return
  118. */
  119. public static Map<String, ?> getAll(Context context)
  120. {
  121. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
  122. Context.MODE_PRIVATE);
  123. return sp.getAll();
  124. }
  125. /**
  126. * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
  127. *
  128. * @author zhy
  129. *
  130. */
  131. private static class SharedPreferencesCompat
  132. {
  133. private static final Method sApplyMethod = findApplyMethod();
  134. /**
  135. * 反射查找apply的方法
  136. *
  137. * @return
  138. */
  139. @SuppressWarnings({ "unchecked", "rawtypes" })
  140. private static Method findApplyMethod()
  141. {
  142. try
  143. {
  144. Class clz = SharedPreferences.Editor.class;
  145. return clz.getMethod("apply");
  146. } catch (NoSuchMethodException e)
  147. {
  148. }
  149. return null;
  150. }
  151. /**
  152. * 如果找到则使用apply执行,否则使用commit
  153. *
  154. * @param editor
  155. */
  156. public static void apply(SharedPreferences.Editor editor)
  157. {
  158. try
  159. {
  160. if (sApplyMethod != null)
  161. {
  162. sApplyMethod.invoke(editor);
  163. return;
  164. }
  165. } catch (IllegalArgumentException e)
  166. {
  167. } catch (IllegalAccessException e)
  168. {
  169. } catch (InvocationTargetException e)
  170. {
  171. }
  172. editor.commit();
  173. }
  174. }
  175. }

对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;

注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit

首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;

所以我们使用apply进行替代,apply异步的进行写入;

但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;

SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~

4、单位转换类 DensityUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.content.Context;
  3. import android.util.TypedValue;
  4. /**
  5. * 常用单位转换的辅助类
  6. *
  7. *
  8. *
  9. */
  10. public class DensityUtils
  11. {
  12. private DensityUtils()
  13. {
  14. /* cannot be instantiated */
  15. throw new UnsupportedOperationException("cannot be instantiated");
  16. }
  17. /**
  18. * dp转px
  19. *
  20. * @param context
  21. * @param val
  22. * @return
  23. */
  24. public static int dp2px(Context context, float dpVal)
  25. {
  26. return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
  27. dpVal, context.getResources().getDisplayMetrics());
  28. }
  29. /**
  30. * sp转px
  31. *
  32. * @param context
  33. * @param val
  34. * @return
  35. */
  36. public static int sp2px(Context context, float spVal)
  37. {
  38. return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
  39. spVal, context.getResources().getDisplayMetrics());
  40. }
  41. /**
  42. * px转dp
  43. *
  44. * @param context
  45. * @param pxVal
  46. * @return
  47. */
  48. public static float px2dp(Context context, float pxVal)
  49. {
  50. final float scale = context.getResources().getDisplayMetrics().density;
  51. return (pxVal / scale);
  52. }
  53. /**
  54. * px转sp
  55. *
  56. * @param fontScale
  57. * @param pxVal
  58. * @return
  59. */
  60. public static float px2sp(Context context, float pxVal)
  61. {
  62. return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
  63. }
  64. }

5、SD卡相关辅助类 SDCardUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import java.io.File;
  3. import android.os.Environment;
  4. import android.os.StatFs;
  5. /**
  6. * SD卡相关的辅助类
  7. *
  8. *
  9. *
  10. */
  11. public class SDCardUtils
  12. {
  13. private SDCardUtils()
  14. {
  15. /* cannot be instantiated */
  16. throw new UnsupportedOperationException("cannot be instantiated");
  17. }
  18. /**
  19. * 判断SDCard是否可用
  20. *
  21. * @return
  22. */
  23. public static boolean isSDCardEnable()
  24. {
  25. return Environment.getExternalStorageState().equals(
  26. Environment.MEDIA_MOUNTED);
  27. }
  28. /**
  29. * 获取SD卡路径
  30. *
  31. * @return
  32. */
  33. public static String getSDCardPath()
  34. {
  35. return Environment.getExternalStorageDirectory().getAbsolutePath()
  36. + File.separator;
  37. }
  38. /**
  39. * 获取SD卡的剩余容量 单位byte
  40. *
  41. * @return
  42. */
  43. public static long getSDCardAllSize()
  44. {
  45. if (isSDCardEnable())
  46. {
  47. StatFs stat = new StatFs(getSDCardPath());
  48. // 获取空闲的数据块的数量
  49. long availableBlocks = (long) stat.getAvailableBlocks() - 4;
  50. // 获取单个数据块的大小(byte)
  51. long freeBlocks = stat.getAvailableBlocks();
  52. return freeBlocks * availableBlocks;
  53. }
  54. return 0;
  55. }
  56. /**
  57. * 获取指定路径所在空间的剩余可用容量字节数,单位byte
  58. *
  59. * @param filePath
  60. * @return 容量字节 SDCard可用空间,内部存储可用空间
  61. */
  62. public static long getFreeBytes(String filePath)
  63. {
  64. // 如果是sd卡的下的路径,则获取sd卡可用容量
  65. if (filePath.startsWith(getSDCardPath()))
  66. {
  67. filePath = getSDCardPath();
  68. } else
  69. {// 如果是内部存储的路径,则获取内存存储的可用容量
  70. filePath = Environment.getDataDirectory().getAbsolutePath();
  71. }
  72. StatFs stat = new StatFs(filePath);
  73. long availableBlocks = (long) stat.getAvailableBlocks() - 4;
  74. return stat.getBlockSize() * availableBlocks;
  75. }
  76. /**
  77. * 获取系统存储路径
  78. *
  79. * @return
  80. */
  81. public static String getRootDirectoryPath()
  82. {
  83. return Environment.getRootDirectory().getAbsolutePath();
  84. }
  85. }

6、屏幕相关辅助类 ScreenUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.graphics.Bitmap;
  5. import android.graphics.Rect;
  6. import android.util.DisplayMetrics;
  7. import android.view.View;
  8. import android.view.WindowManager;
  9. /**
  10. * 获得屏幕相关的辅助类
  11. *
  12. *
  13. *
  14. */
  15. public class ScreenUtils
  16. {
  17. private ScreenUtils()
  18. {
  19. /* cannot be instantiated */
  20. throw new UnsupportedOperationException("cannot be instantiated");
  21. }
  22. /**
  23. * 获得屏幕高度
  24. *
  25. * @param context
  26. * @return
  27. */
  28. public static int getScreenWidth(Context context)
  29. {
  30. WindowManager wm = (WindowManager) context
  31. .getSystemService(Context.WINDOW_SERVICE);
  32. DisplayMetrics outMetrics = new DisplayMetrics();
  33. wm.getDefaultDisplay().getMetrics(outMetrics);
  34. return outMetrics.widthPixels;
  35. }
  36. /**
  37. * 获得屏幕宽度
  38. *
  39. * @param context
  40. * @return
  41. */
  42. public static int getScreenHeight(Context context)
  43. {
  44. WindowManager wm = (WindowManager) context
  45. .getSystemService(Context.WINDOW_SERVICE);
  46. DisplayMetrics outMetrics = new DisplayMetrics();
  47. wm.getDefaultDisplay().getMetrics(outMetrics);
  48. return outMetrics.heightPixels;
  49. }
  50. /**
  51. * 获得状态栏的高度
  52. *
  53. * @param context
  54. * @return
  55. */
  56. public static int getStatusHeight(Context context)
  57. {
  58. int statusHeight = -1;
  59. try
  60. {
  61. Class<?> clazz = Class.forName("com.android.internal.R$dimen");
  62. Object object = clazz.newInstance();
  63. int height = Integer.parseInt(clazz.getField("status_bar_height")
  64. .get(object).toString());
  65. statusHeight = context.getResources().getDimensionPixelSize(height);
  66. } catch (Exception e)
  67. {
  68. e.printStackTrace();
  69. }
  70. return statusHeight;
  71. }
  72. /**
  73. * 获取当前屏幕截图,包含状态栏
  74. *
  75. * @param activity
  76. * @return
  77. */
  78. public static Bitmap snapShotWithStatusBar(Activity activity)
  79. {
  80. View view = activity.getWindow().getDecorView();
  81. view.setDrawingCacheEnabled(true);
  82. view.buildDrawingCache();
  83. Bitmap bmp = view.getDrawingCache();
  84. int width = getScreenWidth(activity);
  85. int height = getScreenHeight(activity);
  86. Bitmap bp = null;
  87. bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
  88. view.destroyDrawingCache();
  89. return bp;
  90. }
  91. /**
  92. * 获取当前屏幕截图,不包含状态栏
  93. *
  94. * @param activity
  95. * @return
  96. */
  97. public static Bitmap snapShotWithoutStatusBar(Activity activity)
  98. {
  99. View view = activity.getWindow().getDecorView();
  100. view.setDrawingCacheEnabled(true);
  101. view.buildDrawingCache();
  102. Bitmap bmp = view.getDrawingCache();
  103. Rect frame = new Rect();
  104. activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
  105. int statusBarHeight = frame.top;
  106. int width = getScreenWidth(activity);
  107. int height = getScreenHeight(activity);
  108. Bitmap bp = null;
  109. bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
  110. - statusBarHeight);
  111. view.destroyDrawingCache();
  112. return bp;
  113. }
  114. }

7、App相关辅助类

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.content.Context;
  3. import android.content.pm.PackageInfo;
  4. import android.content.pm.PackageManager;
  5. import android.content.pm.PackageManager.NameNotFoundException;
  6. /**
  7. * 跟App相关的辅助类
  8. *
  9. *
  10. *
  11. */
  12. public class AppUtils
  13. {
  14. private AppUtils()
  15. {
  16. /* cannot be instantiated */
  17. throw new UnsupportedOperationException("cannot be instantiated");
  18. }
  19. /**
  20. * 获取应用程序名称
  21. */
  22. public static String getAppName(Context context)
  23. {
  24. try
  25. {
  26. PackageManager packageManager = context.getPackageManager();
  27. PackageInfo packageInfo = packageManager.getPackageInfo(
  28. context.getPackageName(), 0);
  29. int labelRes = packageInfo.applicationInfo.labelRes;
  30. return context.getResources().getString(labelRes);
  31. } catch (NameNotFoundException e)
  32. {
  33. e.printStackTrace();
  34. }
  35. return null;
  36. }
  37. /**
  38. * [获取应用程序版本名称信息]
  39. *
  40. * @param context
  41. * @return 当前应用的版本名称
  42. */
  43. public static String getVersionName(Context context)
  44. {
  45. try
  46. {
  47. PackageManager packageManager = context.getPackageManager();
  48. PackageInfo packageInfo = packageManager.getPackageInfo(
  49. context.getPackageName(), 0);
  50. return packageInfo.versionName;
  51. } catch (NameNotFoundException e)
  52. {
  53. e.printStackTrace();
  54. }
  55. return null;
  56. }
  57. }

8、软键盘相关辅助类KeyBoardUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.content.Context;
  3. import android.view.inputmethod.InputMethodManager;
  4. import android.widget.EditText;
  5. /**
  6. * 打开或关闭软键盘
  7. *
  8. * @author zhy
  9. *
  10. */
  11. public class KeyBoardUtils
  12. {
  13. /**
  14. * 打卡软键盘
  15. *
  16. * @param mEditText
  17. *            输入框
  18. * @param mContext
  19. *            上下文
  20. */
  21. public static void openKeybord(EditText mEditText, Context mContext)
  22. {
  23. InputMethodManager imm = (InputMethodManager) mContext
  24. .getSystemService(Context.INPUT_METHOD_SERVICE);
  25. imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
  26. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
  27. InputMethodManager.HIDE_IMPLICIT_ONLY);
  28. }
  29. /**
  30. * 关闭软键盘
  31. *
  32. * @param mEditText
  33. *            输入框
  34. * @param mContext
  35. *            上下文
  36. */
  37. public static void closeKeybord(EditText mEditText, Context mContext)
  38. {
  39. InputMethodManager imm = (InputMethodManager) mContext
  40. .getSystemService(Context.INPUT_METHOD_SERVICE);
  41. imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
  42. }
  43. }

9、网络相关辅助类 NetUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.net.ConnectivityManager;
  7. import android.net.NetworkInfo;
  8. /**
  9. * 跟网络相关的工具类
  10. *
  11. *
  12. *
  13. */
  14. public class NetUtils
  15. {
  16. private NetUtils()
  17. {
  18. /* cannot be instantiated */
  19. throw new UnsupportedOperationException("cannot be instantiated");
  20. }
  21. /**
  22. * 判断网络是否连接
  23. *
  24. * @param context
  25. * @return
  26. */
  27. public static boolean isConnected(Context context)
  28. {
  29. ConnectivityManager connectivity = (ConnectivityManager) context
  30. .getSystemService(Context.CONNECTIVITY_SERVICE);
  31. if (null != connectivity)
  32. {
  33. NetworkInfo info = connectivity.getActiveNetworkInfo();
  34. if (null != info && info.isConnected())
  35. {
  36. if (info.getState() == NetworkInfo.State.CONNECTED)
  37. {
  38. return true;
  39. }
  40. }
  41. }
  42. return false;
  43. }
  44. /**
  45. * 判断是否是wifi连接
  46. */
  47. public static boolean isWifi(Context context)
  48. {
  49. ConnectivityManager cm = (ConnectivityManager) context
  50. .getSystemService(Context.CONNECTIVITY_SERVICE);
  51. if (cm == null)
  52. return false;
  53. return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
  54. }
  55. /**
  56. * 打开网络设置界面
  57. */
  58. public static void openSetting(Activity activity)
  59. {
  60. Intent intent = new Intent("/");
  61. ComponentName cm = new ComponentName("com.android.settings",
  62. "com.android.settings.WirelessSettings");
  63. intent.setComponent(cm);
  64. intent.setAction("android.intent.action.VIEW");
  65. activity.startActivityForResult(intent, 0);
  66. }
  67. }

10、Http相关辅助类 HttpUtils

[java]  view plain copy
  1. package com.zhy.utils;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.PrintWriter;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. /**
  11. * Http请求的工具类
  12. *
  13. * @author zhy
  14. *
  15. */
  16. public class HttpUtils
  17. {
  18. private static final int TIMEOUT_IN_MILLIONS = 5000;
  19. public interface CallBack
  20. {
  21. void onRequestComplete(String result);
  22. }
  23. /**
  24. * 异步的Get请求
  25. *
  26. * @param urlStr
  27. * @param callBack
  28. */
  29. public static void doGetAsyn(final String urlStr, final CallBack callBack)
  30. {
  31. new Thread()
  32. {
  33. public void run()
  34. {
  35. try
  36. {
  37. String result = doGet(urlStr);
  38. if (callBack != null)
  39. {
  40. callBack.onRequestComplete(result);
  41. }
  42. } catch (Exception e)
  43. {
  44. e.printStackTrace();
  45. }
  46. };
  47. }.start();
  48. }
  49. /**
  50. * 异步的Post请求
  51. * @param urlStr
  52. * @param params
  53. * @param callBack
  54. * @throws Exception
  55. */
  56. public static void doPostAsyn(final String urlStr, final String params,
  57. final CallBack callBack) throws Exception
  58. {
  59. new Thread()
  60. {
  61. public void run()
  62. {
  63. try
  64. {
  65. String result = doPost(urlStr, params);
  66. if (callBack != null)
  67. {
  68. callBack.onRequestComplete(result);
  69. }
  70. } catch (Exception e)
  71. {
  72. e.printStackTrace();
  73. }
  74. };
  75. }.start();
  76. }
  77. /**
  78. * Get请求,获得返回数据
  79. *
  80. * @param urlStr
  81. * @return
  82. * @throws Exception
  83. */
  84. public static String doGet(String urlStr)
  85. {
  86. URL url = null;
  87. HttpURLConnection conn = null;
  88. InputStream is = null;
  89. ByteArrayOutputStream baos = null;
  90. try
  91. {
  92. url = new URL(urlStr);
  93. conn = (HttpURLConnection) url.openConnection();
  94. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
  95. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
  96. conn.setRequestMethod("GET");
  97. conn.setRequestProperty("accept", "*/*");
  98. conn.setRequestProperty("connection", "Keep-Alive");
  99. if (conn.getResponseCode() == 200)
  100. {
  101. is = conn.getInputStream();
  102. baos = new ByteArrayOutputStream();
  103. int len = -1;
  104. byte[] buf = new byte[128];
  105. while ((len = is.read(buf)) != -1)
  106. {
  107. baos.write(buf, 0, len);
  108. }
  109. baos.flush();
  110. return baos.toString();
  111. } else
  112. {
  113. throw new RuntimeException(" responseCode is not 200 ... ");
  114. }
  115. } catch (Exception e)
  116. {
  117. e.printStackTrace();
  118. } finally
  119. {
  120. try
  121. {
  122. if (is != null)
  123. is.close();
  124. } catch (IOException e)
  125. {
  126. }
  127. try
  128. {
  129. if (baos != null)
  130. baos.close();
  131. } catch (IOException e)
  132. {
  133. }
  134. conn.disconnect();
  135. }
  136. return null ;
  137. }
  138. /**
  139. * 向指定 URL 发送POST方法的请求
  140. *
  141. * @param url
  142. *            发送请求的 URL
  143. * @param param
  144. *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  145. * @return 所代表远程资源的响应结果
  146. * @throws Exception
  147. */
  148. public static String doPost(String url, String param)
  149. {
  150. PrintWriter out = null;
  151. BufferedReader in = null;
  152. String result = "";
  153. try
  154. {
  155. URL realUrl = new URL(url);
  156. // 打开和URL之间的连接
  157. HttpURLConnection conn = (HttpURLConnection) realUrl
  158. .openConnection();
  159. // 设置通用的请求属性
  160. conn.setRequestProperty("accept", "*/*");
  161. conn.setRequestProperty("connection", "Keep-Alive");
  162. conn.setRequestMethod("POST");
  163. conn.setRequestProperty("Content-Type",
  164. "application/x-www-form-urlencoded");
  165. conn.setRequestProperty("charset", "utf-8");
  166. conn.setUseCaches(false);
  167. // 发送POST请求必须设置如下两行
  168. conn.setDoOutput(true);
  169. conn.setDoInput(true);
  170. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
  171. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
  172. if (param != null && !param.trim().equals(""))
  173. {
  174. // 获取URLConnection对象对应的输出流
  175. out = new PrintWriter(conn.getOutputStream());
  176. // 发送请求参数
  177. out.print(param);
  178. // flush输出流的缓冲
  179. out.flush();
  180. }
  181. // 定义BufferedReader输入流来读取URL的响应
  182. in = new BufferedReader(
  183. new InputStreamReader(conn.getInputStream()));
  184. String line;
  185. while ((line = in.readLine()) != null)
  186. {
  187. result += line;
  188. }
  189. } catch (Exception e)
  190. {
  191. e.printStackTrace();
  192. }
  193. // 使用finally块来关闭输出流、输入流
  194. finally
  195. {
  196. try
  197. {
  198. if (out != null)
  199. {
  200. out.close();
  201. }
  202. if (in != null)
  203. {
  204. in.close();
  205. }
  206. } catch (IOException ex)
  207. {
  208. ex.printStackTrace();
  209. }
  210. }
  211. return result;
  212. }
  213. }

如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~

源码点击下载

11. Android 进度提示圆圈

protected AlertDialog mProgressDialog;public void showDialog(){mProgressDialog = createProgressDialog(this);if((mProgressDialog != null) && !mProgressDialog.isShowing()){try{mProgressDialog.show();LayoutInflater inflater = LayoutInflater.from(this);View v = inflater.inflate(R.layout.xct_lthj_layout_dialog_progressbar,null);Window window = mProgressDialog.getWindow();WindowManager.LayoutParams lp = window.getAttributes();// 设置透明度为0.3lp.alpha = 1.0f;// 设置暗色度lp.dimAmount = 0.0f;lp.gravity = Gravity.CENTER;window.setAttributes(lp);window.setContentView(v);mProgressDialog.setOnKeyListener(MyKeyListener);}catch(BadTokenException e){// TODO check WHY!e.printStackTrace();}}  }public OnKeyListener MyKeyListener = new OnKeyListener() {@Overridepublic boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_SEARCH) {return true;}return false;}};protected AlertDialog createProgressDialog(Context pContext) {AlertDialog.Builder builder = new AlertDialog.Builder(pContext);final AlertDialog progressDialog = builder.create();progressDialog.setCanceledOnTouchOutside(false);return progressDialog;}public void closeDialog(){if(mProgressDialog != null && mProgressDialog.isShowing()){mProgressDialog.dismiss();}}

12、Toast工具类2

package com.zftlive.android.tools;import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;import com.zftlive.android.MApplication;/*** 自定义Toast控件* @author 曾繁添* @version 1.0*/
public class ToolToast {private static Toast mToast;private static Handler mHandler = new Handler();private static Runnable r = new Runnable() {public void run() {mToast.cancel();}}; /*** 弹出较长时间提示信息* @param context 上下文对象* @param msg 要显示的信息*/public static void showLong(Context context, String msg){buildToast(context,msg,Toast.LENGTH_LONG).show();}/*** 弹出较长时间提示信息* @param msg 要显示的信息*/public static void showLong(String msg){buildToast(MApplication.gainContext(),msg,Toast.LENGTH_LONG).show();}/*** 弹出较短时间提示信息* @param context 上下文对象* @param msg 要显示的信息*/public static void showShort(Context context, String msg){buildToast(context,msg,Toast.LENGTH_SHORT).show();}/*** 弹出较短时间提示信息* @param msg 要显示的信息*/public static void showShort(String msg){buildToast(MApplication.gainContext(),msg,Toast.LENGTH_SHORT).show();}/*** 构造Toast* @param context 上下文* @return*/private static Toast buildToast(Context context,String msg,int duration){return buildToast(context,msg,duration,"#000000",16);}/*** 构造Toast* @param context 上下文* @param msg 消息* @param duration 显示时间* @param bgColor 背景颜色* @return*/public static Toast buildToast(Context context,String msg,int duration,String bgColor){return buildToast(context,msg,duration,bgColor,16);}/*** 构造Toast* @param context 上下文* @param msg    消息* @param duration 显示时间* @param bgColor 背景颜色* @param textSp  文字大小* @return*/public static Toast buildToast(Context context,String msg,int duration,String bgColor,int textSp){return buildToast(context,msg,duration,bgColor,textSp,10);}/*** 构造Toast* @param context 上下文* @param msg    消息* @param duration 显示时间* @param bgColor 背景颜色* @param textSp  文字大小* @param cornerRadius  四边圆角弧度* @return*/public static Toast buildToast(Context context,String msg,int duration,String bgColor,int textSp,int cornerRadius){mHandler.removeCallbacks(r);if(null == mToast){//构建ToastmToast = Toast.makeText(context, null, duration);mToast.setGravity(Gravity.CENTER, 0, 0);//取消toastmHandler.postDelayed(r, duration);}//设置Toast文字TextView tv = new TextView(context);int dpPadding = ToolUnit.dipTopx(10);tv.setPadding(dpPadding, dpPadding, dpPadding, dpPadding);tv.setGravity(Gravity.CENTER);tv.setText(msg);tv.setTextColor(Color.WHITE);tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSp);//Toast文字TextView容器LinearLayout mLayout = new LinearLayout(context);GradientDrawable shape = new GradientDrawable();shape.setColor(Color.parseColor(bgColor));shape.setCornerRadius(cornerRadius);shape.setStroke(1, Color.parseColor(bgColor));shape.setAlpha(180);mLayout.setBackground(shape);mLayout.setOrientation(LinearLayout.VERTICAL);LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);  //设置layout_gravityparams.gravity = Gravity.CENTER;  mLayout.setLayoutParams(params);//设置gravitymLayout.setGravity(Gravity.CENTER);mLayout.addView(tv);//将自定义View覆盖Toast的ViewmToast.setView(mLayout);return mToast;}
}

13、图片工具类

package com.zftlive.android.tools;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Random;import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.media.ExifInterface;
import android.view.View;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zftlive.android.config.SysEnv;/*** 图片工具类* @author 曾繁添* @version 1.0*/
public class ToolPicture {/*** 截取应用程序界面(去除状态栏)* @param activity 界面Activity* @return Bitmap对象*/public static Bitmap takeScreenShot(Activity activity){  View view =activity.getWindow().getDecorView();  view.setDrawingCacheEnabled(true);  view.buildDrawingCache();  Bitmap bitmap = view.getDrawingCache();  Rect rect = new Rect();  activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);  int statusBarHeight = rect.top;  /*** *WindowManager windowMgr = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);windowMgr.getDefaultDisplay().getMetrics(mDisplayMetrics);return mDisplayMetrics;*/Bitmap bitmap2 = Bitmap.createBitmap(bitmap,0,statusBarHeight, SysEnv.SCREEN_WIDTH, SysEnv.SCREEN_HEIGHT - statusBarHeight);  view.destroyDrawingCache();  return bitmap2;  }/*** 截取应用程序界面* @param activity 界面Activity* @return Bitmap对象*/public static Bitmap takeFullScreenShot(Activity activity){  activity.getWindow().getDecorView().setDrawingCacheEnabled(true);Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();View view = activity.getWindow().getDecorView();Bitmap bmp2 = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);//view.draw(new Canvas(bmp2));//bmp就是截取的图片了,可通过bmp.compress(CompressFormat.PNG, 100, new FileOutputStream(file));把图片保存为文件。//1、得到状态栏高度Rect rect = new Rect();view.getWindowVisibleDisplayFrame(rect);int statusBarHeight = rect.top;System.out.println("状态栏高度:" + statusBarHeight);//2、得到标题栏高度int wintop = activity.getWindow().findViewById(android.R.id.content).getTop();int titleBarHeight = wintop - statusBarHeight;System.out.println("标题栏高度:" + titleBarHeight);//      //把两个bitmap合到一起
//      Bitmap bmpall=Biatmap.createBitmap(width,height,Config.ARGB_8888);
//      Canvas canvas=new Canvas(bmpall);
//      canvas.drawBitmap(bmp1,x,y,paint);
//      canvas.drawBitmap(bmp2,x,y,paint);return bmp;  }/*** 根据指定内容生成自定义宽高的二维码图片 * @param content 需要生成二维码的内容* @param width 二维码宽度* @param height 二维码高度* @throws WriterException 生成二维码异常*/public static Bitmap makeQRImage(String content, int width, int height)throws WriterException {// 判断URL合法性if (!ToolString.isNoBlankAndNoNull(content))return null;Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 图像数据转换,使用了矩阵转换BitMatrix bitMatrix = new QRCodeWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);int[] pixels = new int[width * height];// 按照二维码的算法,逐个生成二维码的图片,两个for循环是图片横列扫描的结果for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {if (bitMatrix.get(x, y))pixels[y * width + x] = 0xff000000;elsepixels[y * width + x] = 0xffffffff;}}// 生成二维码图片的格式,使用ARGB_8888Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);bitmap.setPixels(pixels, 0, width, 0, 0, width, height);return bitmap;}/*** 读取图片属性:旋转的角度* * @param path 图片绝对路径* @return degree 旋转的角度* @throws IOException*/public static int gainPictureDegree(String path) throws Exception {int degree = 0;try {ExifInterface exifInterface = new ExifInterface(path);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;}} catch (Exception e) {throw(e);}return degree;}/*** 旋转图片 * @param angle 角度* @param bitmap 源bitmap* @return Bitmap 旋转角度之后的bitmap*/  public static Bitmap rotaingBitmap(int angle,Bitmap bitmap) {  //旋转图片 动作   Matrix matrix = new Matrix();;  matrix.postRotate(angle);  //重新构建BitmapBitmap resizedBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix, true);  return resizedBitmap;  }/*** Drawable转成Bitmap * @param drawable* @return*/public static Bitmap drawableToBitmap(Drawable drawable) {if (drawable instanceof BitmapDrawable) {return ((BitmapDrawable) drawable).getBitmap();} else if (drawable instanceof NinePatchDrawable) {Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());drawable.draw(canvas);return bitmap;} else {return null;}}/*** 从资源文件中获取图片* @param context 上下文* @param drawableId 资源文件id* @return*/public static Bitmap gainBitmap(Context context,int drawableId){Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId);return bmp;}/*** 灰白图片(去色)* @param bitmap 需要灰度的图片* @return 去色之后的图片*/public static Bitmap toBlack(Bitmap bitmap) {Bitmap resultBMP = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),Bitmap.Config.RGB_565);Canvas c = new Canvas(resultBMP);Paint paint = new Paint();ColorMatrix cm = new ColorMatrix();cm.setSaturation(0);ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);paint.setColorFilter(f);c.drawBitmap(bitmap, 0, 0, paint);return resultBMP;}/*** 将bitmap转成 byte数组* * @param bitmap* @return*/public static byte[] toBtyeArray(Bitmap bitmap) {ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);return baos.toByteArray();}/*** 将byte数组转成 bitmap* * @param b* @return*/public static Bitmap bytesToBimap(byte[] b) {if (b.length != 0) {return BitmapFactory.decodeByteArray(b, 0, b.length);} else {return null;}}/*** 将Bitmap转换成指定大小* * @param bitmap 需要改变大小的图片* @param width 宽* @param height 高* @return*/public static Bitmap createBitmapBySize(Bitmap bitmap, int width, int height) {return Bitmap.createScaledBitmap(bitmap, width, height, true);}/*** 在图片右下角添加水印* @param srcBMP 原图* @param markBMP 水印图片* @return 合成水印后的图片*/public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) {if (srcBMP == null) {return null;}// 创建一个新的和SRC长度宽度一样的位图Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(), srcBMP.getHeight(), Config.ARGB_8888);Canvas cv = new Canvas(newb);// 在 0,0坐标开始画入原图cv.drawBitmap(srcBMP, 0, 0, null);// 在原图的右下角画入水印cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() + 5, srcBMP.getHeight() - markBMP.getHeight() + 5, null);// 保存cv.save(Canvas.ALL_SAVE_FLAG);// 存储cv.restore();return newb;}/*** 将图片转成指定弧度(角度)的图片* * @param bitmap 需要修改的图片* @param pixels 圆角的弧度* @return 圆角图片*/public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);//根据图片创建画布Canvas canvas = new Canvas(output);final Paint paint = new Paint();final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());final RectF rectF = new RectF(rect);final float roundPx = pixels;paint.setAntiAlias(true);canvas.drawARGB(0, 0, 0, 0);paint.setColor(0xff424242);canvas.drawRoundRect(rectF, roundPx, roundPx, paint);paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));canvas.drawBitmap(bitmap, rect, rect, paint);return output;}/*** 缩放图片* * @param bmp 需要缩放的图片源* @param newW 需要缩放成的图片宽度* @param newH 需要缩放成的图片高度* @return 缩放后的图片*/public static Bitmap zoom(Bitmap bmp, int newW, int newH) {// 获得图片的宽高int width = bmp.getWidth();int height = bmp.getHeight();// 计算缩放比例float scaleWidth = ((float) newW) / width;float scaleHeight = ((float) newH) / height;// 取得想要缩放的matrix参数Matrix matrix = new Matrix();matrix.postScale(scaleWidth, scaleHeight);// 得到新的图片Bitmap newbm = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix,true);return newbm;}/*** 获得倒影的图片* @param bitmap 原始图片* @return 带倒影的图片*/public static Bitmap makeReflectionImage(Bitmap bitmap){  final int reflectionGap = 4;  int width = bitmap.getWidth();  int height = bitmap.getHeight();  Matrix matrix = new Matrix();  matrix.preScale(1, -1);  Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height/2, width, height/2, matrix, false);  Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888);  Paint deafalutPaint = new Paint();  Canvas canvas = new Canvas(bitmapWithReflection);  canvas.drawBitmap(bitmap, 0, 0, null);  canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint);  canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);  Paint paint = new Paint();  LinearGradient shader = new LinearGradient(0,bitmap.getHeight(),0,bitmapWithReflection.getHeight()+reflectionGap,0x70ffffff,0x00ffffff,TileMode.CLAMP);  paint.setShader(shader);  paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));  canvas.drawRect(0,height,width,bitmapWithReflection.getHeight()+reflectionGap,paint);  return bitmapWithReflection;  }  /*** 获取验证码图片* @param width 验证码宽度* @param height 验证码高度* @return 验证码Bitmap对象*/public synchronized static Bitmap makeValidateCode(int width, int height){return ValidateCodeGenerator.createBitmap(width, height);}/*** 获取验证码值* @return 验证码字符串*/public synchronized static String gainValidateCodeValue(){return ValidateCodeGenerator.getCode();}/*** 随机生成验证码内部类**/final static class ValidateCodeGenerator{private static final char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};//default settingsprivate static final int DEFAULT_CODE_LENGTH = 4;private static final int DEFAULT_FONT_SIZE = 20;private static final int DEFAULT_LINE_NUMBER = 3;private static final int BASE_PADDING_LEFT = 5, RANGE_PADDING_LEFT = 10, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 10;private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 30;//variablesprivate static String value;private static int padding_left, padding_top;private static Random random = new Random();public static Bitmap createBitmap(int width,int height) {padding_left = 0;//创建画布Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bp);//随机生成验证码字符StringBuilder buffer = new StringBuilder();for (int i = 0; i < DEFAULT_CODE_LENGTH; i++) {buffer.append(CHARS[random.nextInt(CHARS.length)]);}value = buffer.toString();//设置颜色c.drawColor(Color.WHITE);//设置画笔大小Paint paint = new Paint();paint.setTextSize(DEFAULT_FONT_SIZE);for (int i = 0; i < value.length(); i++) {//随机样式randomTextStyle(paint);padding_left += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);padding_top = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);c.drawText(value.charAt(i) + "", padding_left, padding_top, paint);}for (int i = 0; i < DEFAULT_LINE_NUMBER; i++) {drawLine(c, paint);}//保存  c.save(Canvas.ALL_SAVE_FLAG);c.restore();return bp;}public static String getCode() {return value;}private static void randomTextStyle(Paint paint) {int color = randomColor(1);paint.setColor(color);paint.setFakeBoldText(random.nextBoolean());//true为粗体,false为非粗体float skewX = random.nextInt(11) / 10;skewX = random.nextBoolean() ? skewX : -skewX;paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜paint.setUnderlineText(true); //true为下划线,false为非下划线paint.setStrikeThruText(true); //true为删除线,false为非删除线}private static void drawLine(Canvas canvas, Paint paint) {int color = randomColor(1);int startX = random.nextInt(DEFAULT_WIDTH);int startY = random.nextInt(DEFAULT_HEIGHT);int stopX = random.nextInt(DEFAULT_WIDTH);int stopY = random.nextInt(DEFAULT_HEIGHT);paint.setStrokeWidth(1);paint.setColor(color);canvas.drawLine(startX, startY, stopX, stopY, paint);}private static int randomColor(int rate) {int red = random.nextInt(256) / rate;int green = random.nextInt(256) / rate;int blue = random.nextInt(256) / rate;return Color.rgb(red, green, blue);}}
}

14、Properties文件 工具类

package com.zftlive.android.tools;import java.io.InputStream;
import java.util.Properties;import android.content.Context;import com.zftlive.android.MApplication;/*** 配置文件工具类* * @author 曾繁添* @version 1.0* */
public final class ToolProperties extends Properties {private static Properties property = new Properties();public static String readAssetsProp(String fileName, String key) {String value = "";try {InputStream in = MApplication.gainContext().getAssets().open(fileName);property.load(in);value = property.getProperty(key);} catch (Exception e1) {e1.printStackTrace();}return value;}public static String readAssetsProp(Context context,String fileName, String key) {String value = "";try {InputStream in = context.getAssets().open(fileName);property.load(in);value = property.getProperty(key);} catch (Exception e1) {e1.printStackTrace();}return value;}public static String readAssetsProp(String fileName, String key,String defaultValue) {String value = "";try {InputStream in = MApplication.gainContext().getAssets().open(fileName);property.load(in);value = property.getProperty(key, defaultValue);} catch (Exception e1) {e1.printStackTrace();}return value;}public static String readAssetsProp(Context context,String fileName, String key,String defaultValue) {String value = "";try {InputStream in = context.getAssets().open(fileName);property.load(in);value = property.getProperty(key, defaultValue);} catch (Exception e1) {e1.printStackTrace();}return value;}
}

15、网络工具类2:network

package com.zftlive.android.tools;import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.Log;/*** 基于静态内部类实现的单例,保证线程安全的网络信息工具类 <per> 使用该工具类之前,记得在AndroidManifest.xml添加权限许可 <xmp>* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />* </xmp> </per>* * 安卓判断网络状态,只需要在相应的Activity的相关方法(onCreat/onResum)调用一行代码即可* NetWorkUtils.getInstance(getActivity()).validateNetWork();* * @author 曾繁添* @version 1.0*/
public class ToolNetwork {public final static String NETWORK_CMNET = "CMNET";public final static String NETWORK_CMWAP = "CMWAP";public final static String NETWORK_WIFI = "WIFI";public final static String TAG = "ToolNetwork";private static NetworkInfo networkInfo = null;private Context mContext = null;private ToolNetwork() {}public static ToolNetwork getInstance() {return SingletonHolder.instance;}public ToolNetwork init(Context context){this.mContext = context;return this;}/*** 判断网络是否可用* * @return 是/否*/public boolean isAvailable() {ConnectivityManager manager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);if (null == manager) {return false;}networkInfo = manager.getActiveNetworkInfo();if (null == networkInfo || !networkInfo.isAvailable()) {return false;}return true;}/*** 判断网络是否已连接* * @return 是/否*/public boolean isConnected() {if (!isAvailable()) {return false;}if (!networkInfo.isConnected()) {return false;}return true;}/*** 检查当前环境网络是否可用,不可用跳转至开启网络界面,不设置网络强制关闭当前Activity*/public void validateNetWork() {if (!isConnected()) {Builder dialogBuilder = new AlertDialog.Builder(mContext);dialogBuilder.setTitle("网络设置");dialogBuilder.setMessage("网络不可用,是否现在设置网络?");dialogBuilder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {((Activity) mContext).startActivityForResult(new Intent(Settings.ACTION_SETTINGS),which);}});dialogBuilder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {dialog.cancel();}});dialogBuilder.create();dialogBuilder.show();}}/*** 获取网络连接信息</br> 无网络:</br> WIFI网络:WIFI</br> WAP网络:CMWAP</br>* NET网络:CMNET</br>* * @return*/public String getNetworkType() {if (isConnected()) {int type = networkInfo.getType();if (ConnectivityManager.TYPE_MOBILE == type) {Log.i(TAG,"networkInfo.getExtraInfo()-->"+ networkInfo.getExtraInfo());if (NETWORK_CMWAP.equals(networkInfo.getExtraInfo().toLowerCase())) {return NETWORK_CMWAP;} else {return NETWORK_CMNET;}} else if (ConnectivityManager.TYPE_WIFI == type) {return NETWORK_WIFI;}}return "";}private static class SingletonHolder {private static ToolNetwork instance = new ToolNetwork();}
}

16、调用系统服务(打电话,发短信,获取相册,调用浏览器。。。)

package com.zftlive.android.tools;import java.io.File;
import java.util.ArrayList;
import java.util.List;import android.app.Activity;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;/*** 手机相关操作API* @author 曾繁添* @version 1.0**/
public class ToolPhone {/*** 直接呼叫指定的号码(需要<uses-permission android:name="android.permission.CALL_PHONE"/>权限)* @param mContext 上下文Context* @param phoneNumber 需要呼叫的手机号码*/public static void callPhone(Context mContext,String phoneNumber){Uri uri = Uri.parse("tel:" + phoneNumber);Intent call = new Intent(Intent.ACTION_CALL, uri);mContext.startActivity(call);}/*** 跳转至拨号界面* @param mContext 上下文Context* @param phoneNumber 需要呼叫的手机号码*/public static void toCallPhoneActivity(Context mContext,String phoneNumber){Uri uri = Uri.parse("tel:" + phoneNumber);Intent call = new Intent(Intent.ACTION_DIAL, uri);mContext.startActivity(call);}/*** 直接调用短信API发送信息(设置监听发送和接收状态)* @param strPhone 手机号码* @param strMsgContext 短信内容*/public static void sendMessage(final Context mContext,final String strPhone,final String strMsgContext){//处理返回的发送状态 String SENT_SMS_ACTION = "SENT_SMS_ACTION";Intent sentIntent = new Intent(SENT_SMS_ACTION);PendingIntent sendIntent= PendingIntent.getBroadcast(mContext, 0, sentIntent,0);// register the Broadcast ReceiversmContext.registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context _context, Intent _intent) {switch (getResultCode()) {case Activity.RESULT_OK:Toast.makeText(mContext,"短信发送成功", Toast.LENGTH_SHORT).show();break;case SmsManager.RESULT_ERROR_GENERIC_FAILURE:break;case SmsManager.RESULT_ERROR_RADIO_OFF:break;case SmsManager.RESULT_ERROR_NULL_PDU:break;}}}, new IntentFilter(SENT_SMS_ACTION));//处理返回的接收状态 String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";// create the deilverIntent parameterIntent deliverIntent = new Intent(DELIVERED_SMS_ACTION);PendingIntent backIntent= PendingIntent.getBroadcast(mContext, 0,deliverIntent, 0);mContext.registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context _context, Intent _intent) {Toast.makeText(mContext,strPhone+"已经成功接收", Toast.LENGTH_SHORT).show();}}, new IntentFilter(DELIVERED_SMS_ACTION));//拆分短信内容(手机短信长度限制)SmsManager smsManager = SmsManager.getDefault();ArrayList<String> msgList = smsManager.divideMessage(strMsgContext);for (String text : msgList) {smsManager.sendTextMessage(strPhone, null, text, sendIntent, backIntent);}}/*** 跳转至发送短信界面(自动设置接收方的号码)* @param mActivity Activity* @param strPhone 手机号码* @param strMsgContext 短信内容*/public static void toSendMessageActivity(Context mContext,String strPhone,String strMsgContext){if(PhoneNumberUtils.isGlobalPhoneNumber(strPhone)){Uri uri = Uri.parse("smsto:" + strPhone);Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);sendIntent.putExtra("sms_body", strMsgContext);mContext.startActivity(sendIntent);}}/*** 跳转至联系人选择界面* @param mContext 上下文* @param requestCode 请求返回区分代码*/public static void toChooseContactsList(Activity mContext,int requestCode){Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);mContext.startActivityForResult(intent, requestCode);}/*** 获取选择的联系人的手机号码* @param mContext 上下文* @param resultCode 请求返回Result状态区分代码* @param data onActivityResult返回的Intent* @return*/public static String getChoosedPhoneNumber(Activity mContext,int resultCode,Intent data) {//返回结果String phoneResult = "";if (Activity.RESULT_OK == resultCode) {Uri uri = data.getData();Cursor mCursor = mContext.managedQuery(uri, null, null, null, null);mCursor.moveToFirst();  int phoneColumn = mCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);int phoneNum = mCursor.getInt(phoneColumn);if (phoneNum > 0) {// 获得联系人的ID号int idColumn = mCursor.getColumnIndex(ContactsContract.Contacts._ID);String contactId = mCursor.getString(idColumn);// 获得联系人的电话号码的cursor;Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "+ contactId, null, null);if (phones.moveToFirst()) {// 遍历所有的电话号码for (; !phones.isAfterLast(); phones.moveToNext()) {int index = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);int typeindex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);int phone_type = phones.getInt(typeindex);String phoneNumber = phones.getString(index);switch (phone_type) {case 2:phoneResult = phoneNumber;break;}}if (!phones.isClosed()) {phones.close();}}}//关闭游标mCursor.close();}return phoneResult;}/*** 跳转至拍照程序界面* @param mContext 上下文* @param requestCode 请求返回Result区分代码*/public static void toCameraActivity(Activity mContext,int requestCode){Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);mContext.startActivityForResult(intent, requestCode);}/*** 跳转至相册选择界面* @param mContext 上下文* @param requestCode */public static void toImagePickerActivity(Activity mContext,int requestCode){Intent intent = new Intent(Intent.ACTION_PICK, null);intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");mContext.startActivityForResult(intent, requestCode);}/*** 获得选中相册的图片* @param mContext 上下文* @param data onActivityResult返回的Intent* @return*/public static Bitmap getChoosedImage(Activity mContext,Intent data){if (data == null) {return null;}Bitmap bm = null;// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口ContentResolver resolver = mContext.getContentResolver();// 此处的用于判断接收的Activity是不是你想要的那个try {Uri originalUri = data.getData(); // 获得图片的uribm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片// 这里开始的第二部分,获取图片的路径:String[] proj = {MediaStore.Images.Media.DATA};// 好像是android多媒体数据库的封装接口,具体的看Android文档Cursor cursor = mContext.managedQuery(originalUri, proj, null, null, null);// 按我个人理解 这个是获得用户选择的图片的索引值int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);// 将光标移至开头 ,这个很重要,不小心很容易引起越界cursor.moveToFirst();// 最后根据索引值获取图片路径String path = cursor.getString(column_index);//不用了关闭游标cursor.close();} catch (Exception e) {Log.e("ToolPhone", e.getMessage());}return bm;}/*** 调用本地浏览器打开一个网页* @param mContext 上下文* @param strSiteUrl 网页地址*/public static void openWebSite(Context mContext,String strSiteUrl){Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(strSiteUrl));  mContext.startActivity(webIntent);}/*** 跳转至系统设置界面* @param mContext 上下文*/public static void toSettingActivity(Context mContext){Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);  mContext.startActivity(settingsIntent);  }/*** 跳转至WIFI设置界面* @param mContext 上下文*/public static void toWIFISettingActivity(Context mContext){Intent wifiSettingsIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);  mContext.startActivity(wifiSettingsIntent); }/*** 启动本地应用打开PDF* @param mContext 上下文* @param filePath 文件路径*/public static void openPDFFile(Context mContext, String filePath) {try {File file = new File(filePath);if (file.exists()) {Uri path = Uri.fromFile(file);Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType(path, "application/pdf");intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);mContext.startActivity(intent);}} catch (Exception e) {Toast.makeText(mContext, "未检测到可打开PDF相关软件", Toast.LENGTH_SHORT).show();}}/*** 启动本地应用打开PDF* @param mContext 上下文* @param filePath 文件路径*/public static void openWordFile(Context mContext, String filePath) {try {File file = new File(filePath);if (file.exists()) {Uri path = Uri.fromFile(file);Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(path, "application/msword");mContext.startActivity(intent);}} catch (Exception e) {Toast.makeText(mContext, "未检测到可打开Word文档相关软件", Toast.LENGTH_SHORT).show();}}/*** 调用WPS打开office文档* http://bbs.wps.cn/thread-22349340-1-1.html* @param mContext 上下文* @param filePath 文件路径*/public static void openOfficeByWPS(Context mContext, String filePath){try {//文件存在性检查File file = new File(filePath);if (!file.exists()) {Toast.makeText(mContext, filePath+"文件路径不存在", Toast.LENGTH_SHORT).show();return;}//检查是否安装WPSString wpsPackageEng = "cn.wps.moffice_eng";//普通版与英文版一样
//          String wpsActivity = "cn.wps.moffice.documentmanager.PreStartActivity";String wpsActivity2 = "cn.wps.moffice.documentmanager.PreStartActivity2";//默认第三方程序启动Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.addCategory(Intent.CATEGORY_DEFAULT);intent.setClassName(wpsPackageEng,wpsActivity2);Uri uri = Uri.fromFile(new File(filePath));intent.setData(uri);mContext.startActivity(intent);}catch (ActivityNotFoundException e){Toast.makeText(mContext, "本地未安装WPS", Toast.LENGTH_SHORT).show();} catch (Exception e) {Toast.makeText(mContext, "打开文档失败", Toast.LENGTH_SHORT).show();}}/*** 判断是否安装指定包名的APP* @param mContext 上下文* @param packageName 包路径* @return*/public static boolean isInstalledApp(Context mContext, String packageName) {if (packageName == null || "".equals(packageName)) {return false;}try {ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);return true;} catch (NameNotFoundException e) {return false;}}/*** 判断是否存在指定的Activity* @param mContext 上下文* @param packageName 包名* @param className activity全路径类名* @return*/public static boolean isExistActivity(Context mContext, String packageName,String className) {Boolean result = true;Intent intent = new Intent();intent.setClassName(packageName, className);if (mContext.getPackageManager().resolveActivity(intent, 0) == null) {result =  false;} else if (intent.resolveActivity(mContext.getPackageManager()) == null) {result =  false;} else {List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);if (list.size() == 0) {result =  false;}}return result;}}

17、文件操作工具 包括sdcard等

package com.zftlive.android.tools;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;/*** 文件工具类* * @author 曾繁添* @version 1.0*/
public class ToolFile {private static final String TAG = ToolFile.class.getSimpleName();/*** 检查是否已挂载SD卡镜像(是否存在SD卡)* * @return*/public static boolean isMountedSDCard() {if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {return true;} else {Log.w(TAG, "SDCARD is not MOUNTED !");return false;}}/*** 获取SD卡剩余容量(单位Byte)* * @return*/public static long gainSDFreeSize() {if (isMountedSDCard()) {// 取得SD卡文件路径File path = Environment.getExternalStorageDirectory();StatFs sf = new StatFs(path.getPath());// 获取单个数据块的大小(Byte)long blockSize = sf.getBlockSize();// 空闲的数据块的数量long freeBlocks = sf.getAvailableBlocks();// 返回SD卡空闲大小return freeBlocks * blockSize; // 单位Byte} else {return 0;}}/*** 获取SD卡总容量(单位Byte)* * @return*/public static long gainSDAllSize() {if (isMountedSDCard()) {// 取得SD卡文件路径File path = Environment.getExternalStorageDirectory();StatFs sf = new StatFs(path.getPath());// 获取单个数据块的大小(Byte)long blockSize = sf.getBlockSize();// 获取所有数据块数long allBlocks = sf.getBlockCount();// 返回SD卡大小(Byte)return allBlocks * blockSize;} else {return 0;}}/*** 获取可用的SD卡路径(若SD卡不没有挂载则返回"")* * @return*/public static String gainSDCardPath() {if (isMountedSDCard()) {File sdcardDir = Environment.getExternalStorageDirectory();if (!sdcardDir.canWrite()) {Log.w(TAG, "SDCARD can not write !");}return sdcardDir.getPath();}return "";}/*** 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件* @param filePath 文件路径*/public static String readFileByLines(String filePath) throws IOException{BufferedReader reader = null;StringBuffer sb = new StringBuffer();try{reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),System.getProperty("file.encoding")));String tempString = null;while ((tempString = reader.readLine()) != null){sb.append(tempString);sb.append("\n");}reader.close();} catch (IOException e){e.printStackTrace();} finally{if (reader != null){reader.close();}}return sb.toString();}/*** 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件* @param filePath 文件路径* @param encoding 写文件编码*/public static String readFileByLines(String filePath,String encoding) throws IOException{BufferedReader reader = null;StringBuffer sb = new StringBuffer();try{reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),encoding));String tempString = null;while ((tempString = reader.readLine()) != null){sb.append(tempString);sb.append("\n");}reader.close();} catch (IOException e){e.printStackTrace();} finally{if (reader != null){reader.close();}}return sb.toString();}/*** 保存内容* @param filePath 文件路径* @param content 保存的内容* @throws IOException*/public static void saveToFile(String filePath,String content) throws IOException{saveToFile(filePath,content,System.getProperty("file.encoding"));}/*** 指定编码保存内容* @param filePath 文件路径* @param content 保存的内容* @param encoding 写文件编码* @throws IOException*/public static void saveToFile(String filePath,String content,String encoding) throws IOException{BufferedWriter writer = null;File file = new File(filePath);try{if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), encoding));writer.write(content);} finally{if (writer != null){writer.close();}}}/*** 追加文本* @param content 需要追加的内容* @param file 待追加文件源* @throws IOException*/public static void appendToFile(String content, File file) throws IOException{appendToFile(content, file, System.getProperty("file.encoding"));}/*** 追加文本* @param content 需要追加的内容* @param file 待追加文件源* @param encoding 文件编码* @throws IOException*/public static void appendToFile(String content, File file, String encoding) throws IOException{BufferedWriter writer = null;try{if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));writer.write(content);} finally{if (writer != null){writer.close();}}}/*** 判断文件是否存在* @param filePath 文件路径* @return 是否存在* @throws Exception*/public static Boolean isExsit(String filePath){Boolean flag = false ;try{File file = new File(filePath);if(file.exists()){flag = true;}}catch(Exception e){System.out.println("判断文件失败-->"+e.getMessage()); } return flag;}/*** 快速读取程序应用包下的文件内容* * @param context*            上下文* @param filename*            文件名称* @return 文件内容* @throws IOException*/public static String read(Context context, String filename) throws IOException {FileInputStream inStream = context.openFileInput(filename);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}byte[] data = outStream.toByteArray();return new String(data);}/*** 读取指定目录文件的文件内容* * @param fileName*            文件名称* @return 文件内容* @throws Exception*/public static String read(String fileName) throws IOException {FileInputStream inStream = new FileInputStream(fileName);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}byte[] data = outStream.toByteArray();return new String(data);}/**** 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件* * @param fileName*            文件名称* @param encoding*            文件编码* @return 字符串内容* @throws IOException*/public static String read(String fileName, String encoding)throws IOException {BufferedReader reader = null;StringBuffer sb = new StringBuffer();try {reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));String tempString = null;while ((tempString = reader.readLine()) != null) {sb.append(tempString);}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {reader.close();}}return sb.toString();}/*** 读取raw目录的文件内容* * @param context*            内容上下文* @param rawFileId*            raw文件名id* @return*/public static String readRawValue(Context context, int rawFileId) {String result = "";try {InputStream is = context.getResources().openRawResource(rawFileId);int len = is.available();byte[] buffer = new byte[len];is.read(buffer);result = new String(buffer, "UTF-8");is.close();} catch (Exception e) {e.printStackTrace();}return result;}/*** 读取assets目录的文件内容* * @param context*            内容上下文* @param fileName*            文件名称,包含扩展名* @return*/public static String readAssetsValue(Context context, String fileName) {String result = "";try {InputStream is = context.getResources().getAssets().open(fileName);int len = is.available();byte[] buffer = new byte[len];is.read(buffer);result = new String(buffer, "UTF-8");is.close();} catch (Exception e) {e.printStackTrace();}return result;}/*** 读取assets目录的文件内容* * @param context*            内容上下文* @param fileName*            文件名称,包含扩展名* @return*/public static List<String> readAssetsListValue(Context context, String fileName) {List<String> list = new ArrayList<String>();try {InputStream in = context.getResources().getAssets().open(fileName);BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));String str = null;while ((str = br.readLine()) != null) {list.add(str);}} catch (IOException e) {e.printStackTrace();}return list;}/*** 获取SharedPreferences文件内容* * @param context*            上下文* @param fileNameNoExt*            文件名称(不用带后缀名)* @return*/public static Map<String, ?> readShrePerface(Context context,String fileNameNoExt) {SharedPreferences preferences = context.getSharedPreferences(fileNameNoExt, Context.MODE_PRIVATE);return preferences.getAll();}/*** 写入SharedPreferences文件内容* * @param context*            上下文* @param fileNameNoExt*            文件名称(不用带后缀名)* @param values*            需要写入的数据Map(String,Boolean,Float,Long,Integer)* @return*/public static void writeShrePerface(Context context, String fileNameNoExt,Map<String, ?> values) {try {SharedPreferences preferences = context.getSharedPreferences(fileNameNoExt, Context.MODE_PRIVATE);SharedPreferences.Editor editor = preferences.edit();for (Iterator iterator = values.entrySet().iterator(); iterator.hasNext();) {Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next();if (entry.getValue() instanceof String) {editor.putString(entry.getKey(), (String) entry.getValue());} else if (entry.getValue() instanceof Boolean) {editor.putBoolean(entry.getKey(),(Boolean) entry.getValue());} else if (entry.getValue() instanceof Float) {editor.putFloat(entry.getKey(), (Float) entry.getValue());} else if (entry.getValue() instanceof Long) {editor.putLong(entry.getKey(), (Long) entry.getValue());} else if (entry.getValue() instanceof Integer) {editor.putInt(entry.getKey(),(Integer) entry.getValue());}}editor.commit();} catch (Exception e) {e.printStackTrace();}}/*** 写入应用程序包files目录下文件* * @param context*            上下文* @param fileName*            文件名称* @param content*            文件内容*/public static void write(Context context, String fileName, String content) {try {FileOutputStream outStream = context.openFileOutput(fileName,Context.MODE_PRIVATE);outStream.write(content.getBytes());outStream.close();} catch (Exception e) {e.printStackTrace();}}/*** 写入应用程序包files目录下文件* * @param context*            上下文* @param fileName*            文件名称* @param content*            文件内容*/public static void write(Context context, String fileName, byte[] content) {try {FileOutputStream outStream = context.openFileOutput(fileName,Context.MODE_PRIVATE);outStream.write(content);outStream.close();} catch (Exception e) {e.printStackTrace();}}/*** 写入应用程序包files目录下文件* * @param context*            上下文* @param fileName*            文件名称* @param modeType*            文件写入模式(Context.MODE_PRIVATE、Context.MODE_APPEND、Context.*            MODE_WORLD_READABLE、Context.MODE_WORLD_WRITEABLE)* @param content*            文件内容*/public static void write(Context context, String fileName, byte[] content,int modeType) {try {FileOutputStream outStream = context.openFileOutput(fileName,modeType);outStream.write(content);outStream.close();} catch (Exception e) {e.printStackTrace();}}/*** 指定编码将内容写入目标文件* * @param target*            目标文件* @param content*            文件内容* @param encoding*            写入文件编码* @throws Exception*/public static void write(File target, String content, String encoding)throws IOException {BufferedWriter writer = null;try {if (!target.getParentFile().exists()) {target.getParentFile().mkdirs();}writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target, false), encoding));writer.write(content);} finally {if (writer != null) {writer.close();}}}/*** 指定目录写入文件内容* @param filePath 文件路径+文件名* @param content 文件内容* @throws IOException*/public static void write(String filePath, byte[] content)throws IOException {FileOutputStream fos = null;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}fos = new FileOutputStream(file);fos.write(content);fos.flush();} finally {if (fos != null) {fos.close();}}}/*** 写入文件* * @param inputStream下载文件的字节流对象* @param filePath文件的存放路径(带文件名称)* @throws IOException */public static File write(InputStream inputStream, String filePath) throws IOException {OutputStream outputStream = null;// 在指定目录创建一个空文件并获取文件对象File mFile = new File(filePath);if (!mFile.getParentFile().exists())mFile.getParentFile().mkdirs();try {outputStream = new FileOutputStream(mFile);byte buffer[] = new byte[4 * 1024];int lenght = 0 ;while ((lenght = inputStream.read(buffer)) > 0) {outputStream.write(buffer,0,lenght);}outputStream.flush();return mFile;} catch (IOException e) {Log.e(TAG, "写入文件失败,原因:"+e.getMessage());throw e;}finally{try {inputStream.close();outputStream.close();} catch (IOException e) {}}}/*** 指定目录写入文件内容* @param filePath 文件路径+文件名* @param content 文件内容* @throws IOException*/public static void saveAsJPEG(Bitmap bitmap,String filePath)throws IOException {FileOutputStream fos = null;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}fos = new FileOutputStream(file);bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fos);fos.flush();} finally {if (fos != null) {fos.close();}}}/*** 指定目录写入文件内容* @param filePath 文件路径+文件名* @param content 文件内容* @throws IOException*/public static void saveAsPNG(Bitmap bitmap,String filePath)throws IOException {FileOutputStream fos = null;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}fos = new FileOutputStream(file);bitmap.compress(Bitmap.CompressFormat.PNG, 100,fos);fos.flush();} finally {if (fos != null) {fos.close();}}}
}

Android开发 几个常用工具类相关推荐

  1. android开发监听媒体播放器,Android开发之媒体播放工具类完整示例

    本文实例讲述了Android开发之媒体播放工具类.分享给大家供大家参考,具体如下: package com.maobang.imsdk.util; import android.media.Media ...

  2. Android开发 无线Wifi+WifiUtil工具类,android开发网格布局

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  3. Android开发:手机震动工具类

    新思路,如果你在做关于通知Notification方便的工作,在涉及到多种通知方式组合时(例如:铃声.轻震动.强震动等),感觉到系统提供的API比较吃力的话,建议可以自己来实现通知效果,根据开发经验, ...

  4. 谷歌的json解析器Gson在Android/Java中的常用工具类

    gson解析器,可实现子类和json字符串之间互转 package com.hulk.ues.core;import android.text.TextUtils; import android.ut ...

  5. android 字体像素转换工具类_Android开发之拼音转换工具类PinyinUtils示例

    本文实例讲述了Android开发之拼音转换工具类PinyinUtils.分享给大家供大家参考,具体如下: 1.首先下载pinyin4j-2.5.0.jar,拷贝到工程的lib目录里 或者点击此处本站下 ...

  6. Android开发之获取常用android设备参数信息

    如下图: 查看工具类:下载apk的方法缺少xutils库,可以自己添加xutils库 package com.mchsdk.paysdk.utils;import android.Manifest; ...

  7. Android移动开发-Android开发日历时常用的农历和公历换算代码工具类

    下面是与Android开发日历时常用的有关农历计算.公历计算.二十四气节相关的代码工具类的代码. Constant.java逻辑代码如下: package com.fukaimei.calendar. ...

  8. Android开发常用工具类集合

    转载自:https://blog.csdn.net/xiaoyi_tdcq/article/details/52902844 Android开发常用工具类集合 android开发中为了避免重复造轮子, ...

  9. xamarin开发android收集的一些常用工具

    #xamarin开发android收集的一些常用工具 工欲善其事,必先利其器,从16年下半年开始做xamarin相关的开发,平时使用的一些工具和google插件给大家分享一下,都有下载地址,持续更新. ...

最新文章

  1. jquery中filter、find、children、contents、contains区别
  2. dj鲜生-30-退出用户的登陆
  3. 使用 BoringSSL 优化 HTTPS 加密算法选择(不同终端加密算法不同)
  4. xmlhttp的状态码收集
  5. apache2.4 php5.5 配置,求助,apache2.4+php5.5,配置好不能运行,错误信息如下
  6. BGP多出口多宿主实验
  7. pythonopencv算法_OpenCV算法精解:基于Python与C++
  8. 联发科MT6763处理器参数MT6763处理器芯片资料下载
  9. JavaScript开发必备!这四款静态代码分析工具你了解吗
  10. racecar 尝试记录
  11. 手把手教你用ArcGIS做张降雨量分布专题图
  12. 人工智能在法律中的应用丨“AI+传统行业”全盘点
  13. MonthCalendar
  14. MYSQL limt随着offset增大效率变低
  15. java计算机毕业设计家教平台系统源码+mysql数据库+系统+lw文档+部署
  16. 移动的项目,在tunnel为888696的情况下创建业务
  17. 计算机图形管线(实时渲染管线)
  18. ubuntu python opencv 实用小技巧小结
  19. 阅读报告Maneuvering periods of 2D quantum walks with the coin operator
  20. php时间戳与date格式转换

热门文章

  1. 【Linux】LVM与磁盘配置
  2. 4G速度的100倍:美国Verizon宣布完成5G无线规范标准制定
  3. 2019 十大国产开源项目来势汹汹
  4. 字符流和字节流的区别
  5. JAVA程序设计2018_重庆大学网院2018年Java程序设计 ( 第1次 )
  6. unity导入音频无法识别
  7. 微信小程序全局变量globalData
  8. 关于 react项目 引入 less不起作用的问题解决
  9. elisa标准曲线怎么做_小编分享做ELISA标准曲线时需要着重注意的几个问题
  10. firewalld 防火墙设置