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

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

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

1、日志工具类L.java

  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统一管理类

  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

  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

  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

  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

  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相关辅助类

  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

  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

  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

    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 开发 常用工具类的更多相关文章

  1. Android开发常用工具类

    来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...

  2. 最全Android开发常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括  HttpUtils.DownloadManagerPro.Safe.ijiami.ShellUtils.Pack ...

  3. Android开发常用工具汇总

    Android开发常用工具汇总,本文章不断更新完善 一.数据库小工具Sqlite Developer  SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它的设计目标是嵌入式的, ...

  4. IOS开发--常用工具类收集整理(Objective-C)(持续更新)

    前言:整理和收集了IOS项目开发常用的工具类,最后也给出了源码下载链接. 这些可复用的工具,一定会给你实际项目开发工作锦上添花,会给你带来大大的工作效率. 重复造轮子的事情,除却自我多练习编码之外,就 ...

  5. Android 开发常用工具合集

    在 Android 开发中经常使用到的小功能,用于记录开发的那些事^_^ 1. 获取 release 和 debug 版本的 SHA1 public static String getSHA1(Con ...

  6. 29个android开发常用的类、方法及接口

    在安卓开发中,我们常常都需要借助各种各样的方法.类和接口来实现相关功能.提升开发效率,但对于初学者而言,什么时候该用什么类.方法和接口呢?下面小编整理了29个,日常开发中比较常用的类.方法.接口及其应 ...

  7. android开发Tost工具类管理(一)

    Tost工具类管理: package com.gzcivil.utils; import android.content.Context; import android.widget.Toast; / ...

  8. java 微信开发 常用工具类(xml传输和解析 json转换对象)

    与微信通信常用工具(xml传输和解析) package com.lownsun.wechatOauth.utl; import java.io.IOException; import java.io. ...

  9. Flutter 实际开发常用工具类(全局提示,请求封装,token缓存,验证码倒计时、常用窗帘动画及布局)

    介绍: 一星期从入门到实际开发经验分享及总结           代码传送门github Flutter是谷歌的移动UI框架,可以快速在iOS和Android上构建高质量的原生用户界面.未来App开发 ...

随机推荐

  1. Radar之获取排列的UITexture数组

    1.定义UITexture二维数组 public UITexture[,] m_UITexture; 2.在 void start() 中分配内存 m_UITexture = , ]; 3.遍历排列的 ...

  2. MUI 微信 和支付宝支付 (前台代码)

    <!-- 校园公告详情界面 用于显示校园公告的详情信息 在校园公告界面点击某一条目后 进入本界面查看详情 --> <!DOCTYPE html> <html> &l ...

  3. Objective之ARC

    http://blog.csdn.net/siemenliu/article/details/7891345

  4. 一致性hash算法——之二

    摘自:http://www.tomkleinpeter.com/2008/03/17/programmers-toolbox-part-3-consistent-hashing/

  5. linux下的./本质

    不知道从什么时候对于./的感觉就是这是一条运行命令,因为你要运行某个文件的时候就用./ 但是这个显然是错误的./表述的是当前目录 .就是表示当前目录的.至于为什么运行当前目录下的 文件需要加上./原因 ...

  6. 在Struts2中配置Action

    在Struts2中配置Action <package>: 1.定义Action使用<package>标签下的<action>标签完成,一个<package&g ...

  7. excel小写金额转换成中文大写

    假设 假设数据在A1单元格 任何一个个单元格输入公式=TEXT(INT(A1),"[dbnum2]")&"元"&IF(INT(A1*10)-IN ...

  8. set集合的用法总结(转)

    python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和 ...

  9. 利用[后台]->[类别管理]为文章前后台添加类别名称【转】

    原网址:http://blog.csdn.net/yanhui_wei/article/details/7943176 1.给专题添加文章时,可以选择类别: 2.给文章模型.图片模型.下载模型的栏目下 ...

  10. activiti5.15中文乱码问题

    解决方式: 1.配置文件插入 <bean id="processEngineConfiguration" class="org.activiti.spring.Sp ...