目录(?)[+]

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】

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

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

1、日志工具类L.java

[java] view plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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. }

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

源码点击下载

Android快速开发系列 10个常用工具类相关推荐

  1. 【转】 Android快速开发系列 10个常用工具类 -- 不错

    原文网址:http://blog.csdn.net/lmj623565791/article/details/38965311 转载请标明出处:http://blog.csdn.net/lmj6235 ...

  2. Android快速开发不可或缺的11个工具类(下载)

    Android快速开发不可或缺的11个工具类(下载) 源码简介 Android快速开发不可或缺的11个辅助类,其中10个来自张鸿洋的博客,1个是我平时积攒的,复制粘贴到你的项目里,添加上包名就可以直接 ...

  3. Android 快速开发系列 打造万能的ListView GridView 适配器

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38902805 ,本文出自[张鸿洋的博客] 1.概述 相信做Android开发的写 ...

  4. 工具类系列---【金融常用工具类】

    工具类代码 import java.math.BigDecimal; import java.text.DecimalFormat;/*** 金融常用工具类*/ public class NumFor ...

  5. java工具类去掉字符串String中的.点。android开发java程序员常用工具类

    下面是工具类详细代码: package com.qq986945193.david;/*** qq986945193 Project* ================================ ...

  6. 9.10 安卓常用工具类之一 对话 ---- DialogUtil

    对话 ---- DialogUtil package com.behe.treasure.util; import android.annotation.SuppressLint; import an ...

  7. 9.10 安卓常用工具类之一 权限 ---- PermissionUtil

    权限 ----  PermissionUtil package com.behe.treasure.util; import android.app.Activity; import android. ...

  8. 9.10 安卓常用工具类之一 定位-----LocationUtils

    定位-----LocationUtils package com.behe.treasure.util; import android.Manifest; import android.annotat ...

  9. android根据ip获取域名_android常用工具类 通过域名获取ip

    /** * 编写多线程程序是为了实现多任务的并发执行,从而能够更好地与用户交互. * 一般有三种方法,Thread,Runnable,Callable. * Runnable和Callable的区别是 ...

最新文章

  1. 用命令行操作 VirtualBox 和 SGD
  2. 【OpenCV3】直线拟合——cv::fitLine()详解
  3. web项目实现mysql增删改查并从前端页面操作
  4. 1-5(思科)交换机配置实战需要注意的地方
  5. 006_Select.sql查询语句
  6. 论文浅尝 | 神经网络与非神经网络简单知识问答方法的强基线分析
  7. [LeetCode] 204. Count Primes
  8. android viewpager监听,viewPager的OnPageChangeListener监听器的方法调用顺序
  9. 感性电路电流计算_电工初学者会正确计算负载功率吗?一篇文章彻底教会你
  10. 深度学习 Deep Learning简介 (二):浅层学习(Shallow Learning)和深度学习(Deep Learning)
  11. 大前研一:聪明人必作的十件事
  12. 百度 bos php,百度BOS云存储上传插件 - 支持客户端直传、服务端中转、分片上传 – 基于ThinkPHP和Bootstrap的极速后台开发框架...
  13. zabbix纯内网环境监控服务器发送邮件报警
  14. 比较两组数据的差异用什么图更直观_科研数据可视化:巧妙运用各种形式的图表...
  15. SPSS多元线性回归
  16. 光年(Light Year Admin)后台管理系统模板
  17. 模拟cmos集成电路(7)
  18. Servlet设置欢迎页面!
  19. tf.less(x,y)
  20. 行业分析:中国企业网盘市场目前现状及未来发展透视

热门文章

  1. OnInit 和 Page_Init 事件有什么不同
  2. owls-uddi-matchmaker安装
  3. 如何计算和控制好项目开发成本?
  4. 支持向量回归预测怎么做_财务预测模型怎么做?这些关键指标,你一定要知道...
  5. java开发怎么打补丁_[Java教程]【NC】出补丁与打补丁
  6. 用计算机进行资料检索工作是,用计算机进行资料检索工作是属于计算机应用中的什么...
  7. ant design vue table 高度自适应_2年Vue项目实战经验汇总!
  8. DynamicDataDisplay 实时曲线图的使用和沿轴移动的效果
  9. UVALive 3942 Remember the Word(字典树+DP)
  10. switch 根据键盘录入成绩 显示分数及判断等级(第一次)