Android快速开发系列 10个常用工具类

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

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

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

1、日志工具类L.java

 
  1. package com.zhy.utils;

  2.  
  3. import android.util.Log;

  4.  
  5. /**

  6. * Log统一管理类

  7. *

  8. *

  9. *

  10. */

  11. public class L

  12. {

  13.  
  14. private L()

  15. {

  16. /* cannot be instantiated */

  17. throw new UnsupportedOperationException("cannot be instantiated");

  18. }

  19.  
  20. public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化

  21. private static final String TAG = "way";

  22.  
  23. // 下面四个是默认tag的函数

  24. public static void i(String msg)

  25. {

  26. if (isDebug)

  27. Log.i(TAG, msg);

  28. }

  29.  
  30. public static void d(String msg)

  31. {

  32. if (isDebug)

  33. Log.d(TAG, msg);

  34. }

  35.  
  36. public static void e(String msg)

  37. {

  38. if (isDebug)

  39. Log.e(TAG, msg);

  40. }

  41.  
  42. public static void v(String msg)

  43. {

  44. if (isDebug)

  45. Log.v(TAG, msg);

  46. }

  47.  
  48. // 下面是传入自定义tag的函数

  49. public static void i(String tag, String msg)

  50. {

  51. if (isDebug)

  52. Log.i(tag, msg);

  53. }

  54.  
  55. public static void d(String tag, String msg)

  56. {

  57. if (isDebug)

  58. Log.i(tag, msg);

  59. }

  60.  
  61. public static void e(String tag, String msg)

  62. {

  63. if (isDebug)

  64. Log.i(tag, msg);

  65. }

  66.  
  67. public static void v(String tag, String msg)

  68. {

  69. if (isDebug)

  70. Log.i(tag, msg);

  71. }

  72. }

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

2、Toast统一管理类 

 
  1. package com.zhy.utils;

  2.  
  3. import android.content.Context;

  4. import android.widget.Toast;

  5.  
  6. /**

  7. * Toast统一管理类

  8. *

  9. */

  10. public class T

  11. {

  12.  
  13. private T()

  14. {

  15. /* cannot be instantiated */

  16. throw new UnsupportedOperationException("cannot be instantiated");

  17. }

  18.  
  19. public static boolean isShow = true;

  20.  
  21. /**

  22. * 短时间显示Toast

  23. *

  24. * @param context

  25. * @param message

  26. */

  27. public static void showShort(Context context, CharSequence message)

  28. {

  29. if (isShow)

  30. Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

  31. }

  32.  
  33. /**

  34. * 短时间显示Toast

  35. *

  36. * @param context

  37. * @param message

  38. */

  39. public static void showShort(Context context, int message)

  40. {

  41. if (isShow)

  42. Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

  43. }

  44.  
  45. /**

  46. * 长时间显示Toast

  47. *

  48. * @param context

  49. * @param message

  50. */

  51. public static void showLong(Context context, CharSequence message)

  52. {

  53. if (isShow)

  54. Toast.makeText(context, message, Toast.LENGTH_LONG).show();

  55. }

  56.  
  57. /**

  58. * 长时间显示Toast

  59. *

  60. * @param context

  61. * @param message

  62. */

  63. public static void showLong(Context context, int message)

  64. {

  65. if (isShow)

  66. Toast.makeText(context, message, Toast.LENGTH_LONG).show();

  67. }

  68.  
  69. /**

  70. * 自定义显示Toast时间

  71. *

  72. * @param context

  73. * @param message

  74. * @param duration

  75. */

  76. public static void show(Context context, CharSequence message, int duration)

  77. {

  78. if (isShow)

  79. Toast.makeText(context, message, duration).show();

  80. }

  81.  
  82. /**

  83. * 自定义显示Toast时间

  84. *

  85. * @param context

  86. * @param message

  87. * @param duration

  88. */

  89. public static void show(Context context, int message, int duration)

  90. {

  91. if (isShow)

  92. Toast.makeText(context, message, duration).show();

  93. }

  94.  
  95. }

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

3、SharedPreferences封装类SPUtils

 
  1. package com.zhy.utils;

  2.  
  3. import java.lang.reflect.InvocationTargetException;

  4. import java.lang.reflect.Method;

  5. import java.util.Map;

  6.  
  7. import android.content.Context;

  8. import android.content.SharedPreferences;

  9.  
  10. public class SPUtils

  11. {

  12. /**

  13. * 保存在手机里面的文件名

  14. */

  15. public static final String FILE_NAME = "share_data";

  16.  
  17. /**

  18. * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法

  19. *

  20. * @param context

  21. * @param key

  22. * @param object

  23. */

  24. public static void put(Context context, String key, Object object)

  25. {

  26.  
  27. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  28. Context.MODE_PRIVATE);

  29. SharedPreferences.Editor editor = sp.edit();

  30.  
  31. if (object instanceof String)

  32. {

  33. editor.putString(key, (String) object);

  34. } else if (object instanceof Integer)

  35. {

  36. editor.putInt(key, (Integer) object);

  37. } else if (object instanceof Boolean)

  38. {

  39. editor.putBoolean(key, (Boolean) object);

  40. } else if (object instanceof Float)

  41. {

  42. editor.putFloat(key, (Float) object);

  43. } else if (object instanceof Long)

  44. {

  45. editor.putLong(key, (Long) object);

  46. } else

  47. {

  48. editor.putString(key, object.toString());

  49. }

  50.  
  51. SharedPreferencesCompat.apply(editor);

  52. }

  53.  
  54. /**

  55. * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值

  56. *

  57. * @param context

  58. * @param key

  59. * @param defaultObject

  60. * @return

  61. */

  62. public static Object get(Context context, String key, Object defaultObject)

  63. {

  64. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  65. Context.MODE_PRIVATE);

  66.  
  67. if (defaultObject instanceof String)

  68. {

  69. return sp.getString(key, (String) defaultObject);

  70. } else if (defaultObject instanceof Integer)

  71. {

  72. return sp.getInt(key, (Integer) defaultObject);

  73. } else if (defaultObject instanceof Boolean)

  74. {

  75. return sp.getBoolean(key, (Boolean) defaultObject);

  76. } else if (defaultObject instanceof Float)

  77. {

  78. return sp.getFloat(key, (Float) defaultObject);

  79. } else if (defaultObject instanceof Long)

  80. {

  81. return sp.getLong(key, (Long) defaultObject);

  82. }

  83.  
  84. return null;

  85. }

  86.  
  87. /**

  88. * 移除某个key值已经对应的值

  89. * @param context

  90. * @param key

  91. */

  92. public static void remove(Context context, String key)

  93. {

  94. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  95. Context.MODE_PRIVATE);

  96. SharedPreferences.Editor editor = sp.edit();

  97. editor.remove(key);

  98. SharedPreferencesCompat.apply(editor);

  99. }

  100.  
  101. /**

  102. * 清除所有数据

  103. * @param context

  104. */

  105. public static void clear(Context context)

  106. {

  107. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  108. Context.MODE_PRIVATE);

  109. SharedPreferences.Editor editor = sp.edit();

  110. editor.clear();

  111. SharedPreferencesCompat.apply(editor);

  112. }

  113.  
  114. /**

  115. * 查询某个key是否已经存在

  116. * @param context

  117. * @param key

  118. * @return

  119. */

  120. public static boolean contains(Context context, String key)

  121. {

  122. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  123. Context.MODE_PRIVATE);

  124. return sp.contains(key);

  125. }

  126.  
  127. /**

  128. * 返回所有的键值对

  129. *

  130. * @param context

  131. * @return

  132. */

  133. public static Map<String, ?> getAll(Context context)

  134. {

  135. SharedPreferences sp = context.getSharedPreferences(FILE_NAME,

  136. Context.MODE_PRIVATE);

  137. return sp.getAll();

  138. }

  139.  
  140. /**

  141. * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类

  142. *

  143. * @author zhy

  144. *

  145. */

  146. private static class SharedPreferencesCompat

  147. {

  148. private static final Method sApplyMethod = findApplyMethod();

  149.  
  150. /**

  151. * 反射查找apply的方法

  152. *

  153. * @return

  154. */

  155. @SuppressWarnings({ "unchecked", "rawtypes" })

  156. private static Method findApplyMethod()

  157. {

  158. try

  159. {

  160. Class clz = SharedPreferences.Editor.class;

  161. return clz.getMethod("apply");

  162. } catch (NoSuchMethodException e)

  163. {

  164. }

  165.  
  166. return null;

  167. }

  168.  
  169. /**

  170. * 如果找到则使用apply执行,否则使用commit

  171. *

  172. * @param editor

  173. */

  174. public static void apply(SharedPreferences.Editor editor)

  175. {

  176. try

  177. {

  178. if (sApplyMethod != null)

  179. {

  180. sApplyMethod.invoke(editor);

  181. return;

  182. }

  183. } catch (IllegalArgumentException e)

  184. {

  185. } catch (IllegalAccessException e)

  186. {

  187. } catch (InvocationTargetException e)

  188. {

  189. }

  190. editor.commit();

  191. }

  192. }

  193.  
  194. }


对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.  
  3. import android.content.Context;

  4. import android.util.TypedValue;

  5.  
  6. /**

  7. * 常用单位转换的辅助类

  8. *

  9. *

  10. *

  11. */

  12. public class DensityUtils

  13. {

  14. private DensityUtils()

  15. {

  16. /* cannot be instantiated */

  17. throw new UnsupportedOperationException("cannot be instantiated");

  18. }

  19.  
  20. /**

  21. * dp转px

  22. *

  23. * @param context

  24. * @param val

  25. * @return

  26. */

  27. public static int dp2px(Context context, float dpVal)

  28. {

  29. return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,

  30. dpVal, context.getResources().getDisplayMetrics());

  31. }

  32.  
  33. /**

  34. * sp转px

  35. *

  36. * @param context

  37. * @param val

  38. * @return

  39. */

  40. public static int sp2px(Context context, float spVal)

  41. {

  42. return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,

  43. spVal, context.getResources().getDisplayMetrics());

  44. }

  45.  
  46. /**

  47. * px转dp

  48. *

  49. * @param context

  50. * @param pxVal

  51. * @return

  52. */

  53. public static float px2dp(Context context, float pxVal)

  54. {

  55. final float scale = context.getResources().getDisplayMetrics().density;

  56. return (pxVal / scale);

  57. }

  58.  
  59. /**

  60. * px转sp

  61. *

  62. * @param fontScale

  63. * @param pxVal

  64. * @return

  65. */

  66. public static float px2sp(Context context, float pxVal)

  67. {

  68. return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);

  69. }

  70.  
  71. }

5、SD卡相关辅助类 SDCardUtils

 
  1. package com.zhy.utils;

  2.  
  3. import java.io.File;

  4.  
  5. import android.os.Environment;

  6. import android.os.StatFs;

  7.  
  8. /**

  9. * SD卡相关的辅助类

  10. *

  11. *

  12. *

  13. */

  14. public class SDCardUtils

  15. {

  16. private SDCardUtils()

  17. {

  18. /* cannot be instantiated */

  19. throw new UnsupportedOperationException("cannot be instantiated");

  20. }

  21.  
  22. /**

  23. * 判断SDCard是否可用

  24. *

  25. * @return

  26. */

  27. public static boolean isSDCardEnable()

  28. {

  29. return Environment.getExternalStorageState().equals(

  30. Environment.MEDIA_MOUNTED);

  31.  
  32. }

  33.  
  34. /**

  35. * 获取SD卡路径

  36. *

  37. * @return

  38. */

  39. public static String getSDCardPath()

  40. {

  41. return Environment.getExternalStorageDirectory().getAbsolutePath()

  42. + File.separator;

  43. }

  44.  
  45. /**

  46. * 获取SD卡的剩余容量 单位byte

  47. *

  48. * @return

  49. */

  50. public static long getSDCardAllSize()

  51. {

  52. if (isSDCardEnable())

  53. {

  54. StatFs stat = new StatFs(getSDCardPath());

  55. // 获取空闲的数据块的数量

  56. long availableBlocks = (long) stat.getAvailableBlocks() - 4;

  57. // 获取单个数据块的大小(byte)

  58. long freeBlocks = stat.getAvailableBlocks();

  59. return freeBlocks * availableBlocks;

  60. }

  61. return 0;

  62. }

  63.  
  64. /**

  65. * 获取指定路径所在空间的剩余可用容量字节数,单位byte

  66. *

  67. * @param filePath

  68. * @return 容量字节 SDCard可用空间,内部存储可用空间

  69. */

  70. public static long getFreeBytes(String filePath)

  71. {

  72. // 如果是sd卡的下的路径,则获取sd卡可用容量

  73. if (filePath.startsWith(getSDCardPath()))

  74. {

  75. filePath = getSDCardPath();

  76. } else

  77. {// 如果是内部存储的路径,则获取内存存储的可用容量

  78. filePath = Environment.getDataDirectory().getAbsolutePath();

  79. }

  80. StatFs stat = new StatFs(filePath);

  81. long availableBlocks = (long) stat.getAvailableBlocks() - 4;

  82. return stat.getBlockSize() * availableBlocks;

  83. }

  84.  
  85. /**

  86. * 获取系统存储路径

  87. *

  88. * @return

  89. */

  90. public static String getRootDirectoryPath()

  91. {

  92. return Environment.getRootDirectory().getAbsolutePath();

  93. }

  94.  
  95.  
  96. }

6、屏幕相关辅助类 ScreenUtils

 
  1. package com.zhy.utils;

  2.  
  3. import android.app.Activity;

  4. import android.content.Context;

  5. import android.graphics.Bitmap;

  6. import android.graphics.Rect;

  7. import android.util.DisplayMetrics;

  8. import android.view.View;

  9. import android.view.WindowManager;

  10.  
  11. /**

  12. * 获得屏幕相关的辅助类

  13. *

  14. *

  15. *

  16. */

  17. public class ScreenUtils

  18. {

  19. private ScreenUtils()

  20. {

  21. /* cannot be instantiated */

  22. throw new UnsupportedOperationException("cannot be instantiated");

  23. }

  24.  
  25. /**

  26. * 获得屏幕高度

  27. *

  28. * @param context

  29. * @return

  30. */

  31. public static int getScreenWidth(Context context)

  32. {

  33. WindowManager wm = (WindowManager) context

  34. .getSystemService(Context.WINDOW_SERVICE);

  35. DisplayMetrics outMetrics = new DisplayMetrics();

  36. wm.getDefaultDisplay().getMetrics(outMetrics);

  37. return outMetrics.widthPixels;

  38. }

  39.  
  40. /**

  41. * 获得屏幕宽度

  42. *

  43. * @param context

  44. * @return

  45. */

  46. public static int getScreenHeight(Context context)

  47. {

  48. WindowManager wm = (WindowManager) context

  49. .getSystemService(Context.WINDOW_SERVICE);

  50. DisplayMetrics outMetrics = new DisplayMetrics();

  51. wm.getDefaultDisplay().getMetrics(outMetrics);

  52. return outMetrics.heightPixels;

  53. }

  54.  
  55. /**

  56. * 获得状态栏的高度

  57. *

  58. * @param context

  59. * @return

  60. */

  61. public static int getStatusHeight(Context context)

  62. {

  63.  
  64. int statusHeight = -1;

  65. try

  66. {

  67. Class<?> clazz = Class.forName("com.android.internal.R$dimen");

  68. Object object = clazz.newInstance();

  69. int height = Integer.parseInt(clazz.getField("status_bar_height")

  70. .get(object).toString());

  71. statusHeight = context.getResources().getDimensionPixelSize(height);

  72. } catch (Exception e)

  73. {

  74. e.printStackTrace();

  75. }

  76. return statusHeight;

  77. }

  78.  
  79. /**

  80. * 获取当前屏幕截图,包含状态栏

  81. *

  82. * @param activity

  83. * @return

  84. */

  85. public static Bitmap snapShotWithStatusBar(Activity activity)

  86. {

  87. View view = activity.getWindow().getDecorView();

  88. view.setDrawingCacheEnabled(true);

  89. view.buildDrawingCache();

  90. Bitmap bmp = view.getDrawingCache();

  91. int width = getScreenWidth(activity);

  92. int height = getScreenHeight(activity);

  93. Bitmap bp = null;

  94. bp = Bitmap.createBitmap(bmp, 0, 0, width, height);

  95. view.destroyDrawingCache();

  96. return bp;

  97.  
  98. }

  99.  
  100. /**

  101. * 获取当前屏幕截图,不包含状态栏

  102. *

  103. * @param activity

  104. * @return

  105. */

  106. public static Bitmap snapShotWithoutStatusBar(Activity activity)

  107. {

  108. View view = activity.getWindow().getDecorView();

  109. view.setDrawingCacheEnabled(true);

  110. view.buildDrawingCache();

  111. Bitmap bmp = view.getDrawingCache();

  112. Rect frame = new Rect();

  113. activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

  114. int statusBarHeight = frame.top;

  115.  
  116. int width = getScreenWidth(activity);

  117. int height = getScreenHeight(activity);

  118. Bitmap bp = null;

  119. bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height

  120. - statusBarHeight);

  121. view.destroyDrawingCache();

  122. return bp;

  123.  
  124. }

  125.  
  126. }

7、App相关辅助类

 
  1. package com.zhy.utils;

  2.  
  3. import android.content.Context;

  4. import android.content.pm.PackageInfo;

  5. import android.content.pm.PackageManager;

  6. import android.content.pm.PackageManager.NameNotFoundException;

  7.  
  8. /**

  9. * 跟App相关的辅助类

  10. *

  11. *

  12. *

  13. */

  14. public class AppUtils

  15. {

  16.  
  17. private AppUtils()

  18. {

  19. /* cannot be instantiated */

  20. throw new UnsupportedOperationException("cannot be instantiated");

  21.  
  22. }

  23.  
  24. /**

  25. * 获取应用程序名称

  26. */

  27. public static String getAppName(Context context)

  28. {

  29. try

  30. {

  31. PackageManager packageManager = context.getPackageManager();

  32. PackageInfo packageInfo = packageManager.getPackageInfo(

  33. context.getPackageName(), 0);

  34. int labelRes = packageInfo.applicationInfo.labelRes;

  35. return context.getResources().getString(labelRes);

  36. } catch (NameNotFoundException e)

  37. {

  38. e.printStackTrace();

  39. }

  40. return null;

  41. }

  42.  
  43. /**

  44. * [获取应用程序版本名称信息]

  45. *

  46. * @param context

  47. * @return 当前应用的版本名称

  48. */

  49. public static String getVersionName(Context context)

  50. {

  51. try

  52. {

  53. PackageManager packageManager = context.getPackageManager();

  54. PackageInfo packageInfo = packageManager.getPackageInfo(

  55. context.getPackageName(), 0);

  56. return packageInfo.versionName;

  57.  
  58. } catch (NameNotFoundException e)

  59. {

  60. e.printStackTrace();

  61. }

  62. return null;

  63. }

  64.  
  65. }

8、软键盘相关辅助类KeyBoardUtils

 
  1. package com.zhy.utils;

  2.  
  3. import android.content.Context;

  4. import android.view.inputmethod.InputMethodManager;

  5. import android.widget.EditText;

  6.  
  7. /**

  8. * 打开或关闭软键盘

  9. *

  10. * @author zhy

  11. *

  12. */

  13. public class KeyBoardUtils

  14. {

  15. /**

  16. * 打卡软键盘

  17. *

  18. * @param mEditText

  19. * 输入框

  20. * @param mContext

  21. * 上下文

  22. */

  23. public static void openKeybord(EditText mEditText, Context mContext)

  24. {

  25. InputMethodManager imm = (InputMethodManager) mContext

  26. .getSystemService(Context.INPUT_METHOD_SERVICE);

  27. imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);

  28. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,

  29. InputMethodManager.HIDE_IMPLICIT_ONLY);

  30. }

  31.  
  32. /**

  33. * 关闭软键盘

  34. *

  35. * @param mEditText

  36. * 输入框

  37. * @param mContext

  38. * 上下文

  39. */

  40. public static void closeKeybord(EditText mEditText, Context mContext)

  41. {

  42. InputMethodManager imm = (InputMethodManager) mContext

  43. .getSystemService(Context.INPUT_METHOD_SERVICE);

  44.  
  45. imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

  46. }

  47. }

9、网络相关辅助类 NetUtils

 
  1. package com.zhy.utils;

  2.  
  3. import android.app.Activity;

  4. import android.content.ComponentName;

  5. import android.content.Context;

  6. import android.content.Intent;

  7. import android.net.ConnectivityManager;

  8. import android.net.NetworkInfo;

  9.  
  10. /**

  11. * 跟网络相关的工具类

  12. *

  13. *

  14. *

  15. */

  16. public class NetUtils

  17. {

  18. private NetUtils()

  19. {

  20. /* cannot be instantiated */

  21. throw new UnsupportedOperationException("cannot be instantiated");

  22. }

  23.  
  24. /**

  25. * 判断网络是否连接

  26. *

  27. * @param context

  28. * @return

  29. */

  30. public static boolean isConnected(Context context)

  31. {

  32.  
  33. ConnectivityManager connectivity = (ConnectivityManager) context

  34. .getSystemService(Context.CONNECTIVITY_SERVICE);

  35.  
  36. if (null != connectivity)

  37. {

  38.  
  39. NetworkInfo info = connectivity.getActiveNetworkInfo();

  40. if (null != info && info.isConnected())

  41. {

  42. if (info.getState() == NetworkInfo.State.CONNECTED)

  43. {

  44. return true;

  45. }

  46. }

  47. }

  48. return false;

  49. }

  50.  
  51. /**

  52. * 判断是否是wifi连接

  53. */

  54. public static boolean isWifi(Context context)

  55. {

  56. ConnectivityManager cm = (ConnectivityManager) context

  57. .getSystemService(Context.CONNECTIVITY_SERVICE);

  58.  
  59. if (cm == null)

  60. return false;

  61. return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

  62.  
  63. }

  64.  
  65. /**

  66. * 打开网络设置界面

  67. */

  68. public static void openSetting(Activity activity)

  69. {

  70. Intent intent = new Intent("/");

  71. ComponentName cm = new ComponentName("com.android.settings",

  72. "com.android.settings.WirelessSettings");

  73. intent.setComponent(cm);

  74. intent.setAction("android.intent.action.VIEW");

  75. activity.startActivityForResult(intent, 0);

  76. }

  77.  
  78. }

10、Http相关辅助类 HttpUtils

 
  1. package com.zhy.utils;

  2.  
  3. import java.io.BufferedReader;

  4. import java.io.ByteArrayOutputStream;

  5. import java.io.IOException;

  6. import java.io.InputStream;

  7. import java.io.InputStreamReader;

  8. import java.io.PrintWriter;

  9. import java.net.HttpURLConnection;

  10. import java.net.URL;

  11.  
  12. /**

  13. * Http请求的工具类

  14. *

  15. * @author zhy

  16. *

  17. */

  18. public class HttpUtils

  19. {

  20.  
  21. private static final int TIMEOUT_IN_MILLIONS = 5000;

  22.  
  23. public interface CallBack

  24. {

  25. void onRequestComplete(String result);

  26. }

  27.  
  28.  
  29. /**

  30. * 异步的Get请求

  31. *

  32. * @param urlStr

  33. * @param callBack

  34. */

  35. public static void doGetAsyn(final String urlStr, final CallBack callBack)

  36. {

  37. new Thread()

  38. {

  39. public void run()

  40. {

  41. try

  42. {

  43. String result = doGet(urlStr);

  44. if (callBack != null)

  45. {

  46. callBack.onRequestComplete(result);

  47. }

  48. } catch (Exception e)

  49. {

  50. e.printStackTrace();

  51. }

  52.  
  53. };

  54. }.start();

  55. }

  56.  
  57. /**

  58. * 异步的Post请求

  59. * @param urlStr

  60. * @param params

  61. * @param callBack

  62. * @throws Exception

  63. */

  64. public static void doPostAsyn(final String urlStr, final String params,

  65. final CallBack callBack) throws Exception

  66. {

  67. new Thread()

  68. {

  69. public void run()

  70. {

  71. try

  72. {

  73. String result = doPost(urlStr, params);

  74. if (callBack != null)

  75. {

  76. callBack.onRequestComplete(result);

  77. }

  78. } catch (Exception e)

  79. {

  80. e.printStackTrace();

  81. }

  82.  
  83. };

  84. }.start();

  85.  
  86. }

  87.  
  88. /**

  89. * Get请求,获得返回数据

  90. *

  91. * @param urlStr

  92. * @return

  93. * @throws Exception

  94. */

  95. public static String doGet(String urlStr)

  96. {

  97. URL url = null;

  98. HttpURLConnection conn = null;

  99. InputStream is = null;

  100. ByteArrayOutputStream baos = null;

  101. try

  102. {

  103. url = new URL(urlStr);

  104. conn = (HttpURLConnection) url.openConnection();

  105. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);

  106. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

  107. conn.setRequestMethod("GET");

  108. conn.setRequestProperty("accept", "*/*");

  109. conn.setRequestProperty("connection", "Keep-Alive");

  110. if (conn.getResponseCode() == 200)

  111. {

  112. is = conn.getInputStream();

  113. baos = new ByteArrayOutputStream();

  114. int len = -1;

  115. byte[] buf = new byte[128];

  116.  
  117. while ((len = is.read(buf)) != -1)

  118. {

  119. baos.write(buf, 0, len);

  120. }

  121. baos.flush();

  122. return baos.toString();

  123. } else

  124. {

  125. throw new RuntimeException(" responseCode is not 200 ... ");

  126. }

  127.  
  128. } catch (Exception e)

  129. {

  130. e.printStackTrace();

  131. } finally

  132. {

  133. try

  134. {

  135. if (is != null)

  136. is.close();

  137. } catch (IOException e)

  138. {

  139. }

  140. try

  141. {

  142. if (baos != null)

  143. baos.close();

  144. } catch (IOException e)

  145. {

  146. }

  147. conn.disconnect();

  148. }

  149.  
  150. return null ;

  151.  
  152. }

  153.  
  154. /**

  155. * 向指定 URL 发送POST方法的请求

  156. *

  157. * @param url

  158. * 发送请求的 URL

  159. * @param param

  160. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

  161. * @return 所代表远程资源的响应结果

  162. * @throws Exception

  163. */

  164. public static String doPost(String url, String param)

  165. {

  166. PrintWriter out = null;

  167. BufferedReader in = null;

  168. String result = "";

  169. try

  170. {

  171. URL realUrl = new URL(url);

  172. // 打开和URL之间的连接

  173. HttpURLConnection conn = (HttpURLConnection) realUrl

  174. .openConnection();

  175. // 设置通用的请求属性

  176. conn.setRequestProperty("accept", "*/*");

  177. conn.setRequestProperty("connection", "Keep-Alive");

  178. conn.setRequestMethod("POST");

  179. conn.setRequestProperty("Content-Type",

  180. "application/x-www-form-urlencoded");

  181. conn.setRequestProperty("charset", "utf-8");

  182. conn.setUseCaches(false);

  183. // 发送POST请求必须设置如下两行

  184. conn.setDoOutput(true);

  185. conn.setDoInput(true);

  186. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);

  187. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

  188.  
  189. if (param != null && !param.trim().equals(""))

  190. {

  191. // 获取URLConnection对象对应的输出流

  192. out = new PrintWriter(conn.getOutputStream());

  193. // 发送请求参数

  194. out.print(param);

  195. // flush输出流的缓冲

  196. out.flush();

  197. }

  198. // 定义BufferedReader输入流来读取URL的响应

  199. in = new BufferedReader(

  200. new InputStreamReader(conn.getInputStream()));

  201. String line;

  202. while ((line = in.readLine()) != null)

  203. {

  204. result += line;

  205. }

  206. } catch (Exception e)

  207. {

  208. e.printStackTrace();

  209. }

  210. // 使用finally块来关闭输出流、输入流

  211. finally

  212. {

  213. try

  214. {

  215. if (out != null)

  216. {

  217. out.close();

  218. }

  219. if (in != null)

  220. {

  221. in.close();

  222. }

  223. } catch (IOException ex)

  224. {

  225. ex.printStackTrace();

  226. }

  227. }

  228. return result;

  229. }

  230. }


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

源码点击下载

猜你喜欢

转载自blog.csdn.net/u010144805/article/details/81221181