当前位置: 首页 > 编程日记 > 正文

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

原文网址:http://blog.csdn.net/lmj623565791/article/details/38965311

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

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

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

1、日志工具类L.java

[java] view plaincopy
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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
在CODE上查看代码片派生到我的代码片
  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. }


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

源码点击下载

转载于:https://www.cnblogs.com/wi100sh/p/5461644.html

相关文章:

CollectionView侧滑刷新

作者 SoDoIt 关注 2017.03.05 16:39 字数 33 阅读 31评论 0喜欢 2ABSideRefresh.gif效仿MJRefresh写的侧滑刷新&#xff0c;原理不讲了&#xff0c;需要的直接看代码 GitHub&#xff1a;https://github.com/wangjingyu0018/ABRefresh.git

函数功能MATLAB

近期一直在查找函数功能之类的题问,现在正好有机会和大家享共一下. 百科名片 录目 简介开展程历要主功能新特性版本分析特色优势开展简介开展程历要主功能新特性版本分析特色优势开展编辑本段 简介 matlab开辟任务面界 编辑本段 开展程历 编辑本段 要主功能 1.数值析分 2.数值和…

[HTTP协议]基础篇-待完结

文章目录输入网址后回车输入网址后回车 简单的浏览器HTTP请求过程&#xff1a; 浏览器从地址栏输入中获取服务器IP地址和端口号浏览器用TCP的三次握手与服务器建立连接浏览器向服务器发送拼好的报文服务器收到报文后处理请求&#xff0c;同样拼好报文再发给浏览器浏览器解析报…

IAR之工程配置

参考 : IAR的Workspace顶部下拉菜单中Debug和Release http://blog.csdn.net/yanpingsz/article/details/5588525 最近买了zigbee模块的开发板回来研究, 其中一个实验程序里面有三个版本, 分别是路由/终端/协调器, 忙活了半天不知道同一个project是如何配置成3个不同的版本的. …

CoreText入坑一

CoreText是Mac OS和iOS系统中处理文本的low-level API, 不管是使用OC还是swift, 实际我们使用CoreText都还是间接或直接使用C语言在写代码。CoreText是iOS和Mac OS中文本处理的根基, TextKit和WebKit都是构建于其上。 一. 基础 1.在使用CoreText编写代码之前, 需要先了解一些基…

mysql连接hang住问题分析

【问题现象】&#xff1a; 1. Linuxc多线程连接mysql数据库&#xff0c;每次都是短连接&#xff0c;操作完后就释放连接&#xff0c;有时候会出现mysql_real_connect挂住的现象 2. 挂住超时mysql_real_connect返回后报错如下&#xff1a;Lostconnection to MySQL s…

【Linux学习笔记】 -- 基本Shell命令

常见的目录名均基于文件系统层级标准(filesystem hierarchy standard&#xff0c;FHS) Linux的四个部分&#xff1a; 1 Linux内核&#xff1a;控制所有硬软件&#xff0c;必要时分配硬件根据需要执行软件 系统内存管理&#xff1a;可用物理内存 创建、管理虚拟内存[交换空间…

【OpenCV】图像代数运算:平均值去噪,减去背景

代数运算&#xff0c;就是对两幅图像的点之间进行加、减、乘、除的运算。四种运算相应的公式为&#xff1a; 代数运算中比较常用的是图像相加和相减。图像相加常用来求平均值去除addtive噪声或者实现二次曝光&#xff08;double-exposure&#xff09;。图像相减用于减去背景或周…

简明 Vim 练级攻略(转)

vim的学习曲线相当的大&#xff08;参看各种文本编辑器的学习曲线&#xff09;&#xff0c;所以&#xff0c;如果你一开始看到的是一大堆VIM的命令分类&#xff0c;你一定会对这个编辑器失去兴趣的。下面的文章翻译自《Learn Vim Progressively》&#xff0c;我觉得这是给新手最…

iOS 的离屏渲染

原文链接&#xff1a;http://www.imlifengfeng.com/blog/?p593OpenGL ES 是一套多功能开放标准的用于嵌入系统的 C-based 的图形库&#xff0c;用于 2D 和 3D 数据的可视化。OpenGL 被设计用来转换一组图形调用功能到底层图形硬件&#xff08;GPU&#xff09;&#xff0c;由 G…

MySQL 常见操作指令

什么是SQL&#xff1f; SQL&#xff08;Structured Query Language&#xff09;用于访问和操作数据库的结构化查询语言。 数据库包含一个或多个表&#xff0c;每个表均有名称标识&#xff0c;包含数据的记录&#xff08;行&#xff09;。 典型的SQL语句 1. SELEC语句 SELE…

iOS 实现点击微信头像效果

来源&#xff1a;伯乐在线 - 小良 如有好文章投稿&#xff0c;请点击 → 这里了解详情 如需转载&#xff0c;发送「转载」二字查看说明 公司产品需要实现点击个人主页头像可以放大头像、缩放头像、保存头像效果&#xff08;和点击微信个人头像类似&#xff09;&#xff0c;故找…

HDU 4292 Food(dinic +拆点)

题目链接 我做的伤心了&#xff0c;不知是模版效率低&#xff0c;还是错了&#xff0c;交上就是TLE&#xff0c;找了份别人的代码&#xff0c;改了好几下终于过了。。 1 #include <cstdio>2 #include <cstring>3 #include <queue>4 #include <map>5 #i…

jQuery中用ajax访问php接口文件

js代码 function ajax_request(){var result;var articleId new Object();articleIdgetArticleId();$.ajax({url: "/topicPage/getComment.php",//请求php文件的路径data:{id:articleId},//请求中要传送的参数,会自动拼接成一个路径&#xff0c;在php中用get方式获取…

Python 数据库操作 psycopg2

文章目录安装基本使用安装 psycopg 是 Python 语言中 PostpreSQL数据库接口 安装环境&#xff1a; Python&#xff1a;v2.7, v3.4~3.8PostGreSQL&#xff1a;7.4~12 pip install psycopg2基本使用 import psycopg2def connect_db(host: str,port: int,database: str,user:…

Android logcat命令详解

一、logcat命令介绍 1.android log系统 2.logcat介绍 logcat是android中的一个命令行工具&#xff0c;可以用于得到程序的log信息 log类是一个日志类&#xff0c;可以在代码中使用logcat打印出消息 常见的日志纪录方法包括&#xff1a;方法 描述 v(String,String) (vervbose)显…

[iOS]如何重新架构 JPVideoPlayer ?

注意&#xff1a;此文为配合 JPVideoPlayer version 2.0 版本发布而写&#xff0c;如果你想了解 2.0 版本的更新内容和所有实现细节&#xff0c;请点击前往 GitHub。 导言&#xff1a;我几个月前写了一个在 UITableView 中滑动 UITableViewCell 播放视频的框架&#xff0c;类似…

函数项目一个超感人的故事:关于swfupload在某些环境下面session丢失的完美解决方案(看完我哭了)...

查了好多资料&#xff0c;发现还是不全&#xff0c;干脆自己整理吧&#xff0c;至少保证在我的做法正确的&#xff0c;以免误导读者&#xff0c;也是给自己做个记录吧&#xff01; 标题吸引到你了吗&#xff1f; 先说一下这个题问成形的原因。大家都晓得 session是靠cookie中的…

【学习笔记】git 使用文档

安装 git # mac 环境 brew install git检查是否安装成功 ➜ ~ git --version git version 2.20.1 (Apple Git-117)卸载 git ➜ ~ which -a git /usr/bin/git ➜ ~ cd /usr/bin ➜ bin sudo rm -rf git*git init 命令 对一个空文件&#xff0c;git 初始化。文件名称增加…

UIBezierPath和CAShapeLayer创建不规则View(Swift 3.0)

最近一个朋友在做图片处理的 App&#xff0c;想要实现类似 MOLDIV App 拼图的UI效果&#xff08;如何创建不规则的 view&#xff09;&#xff0c;就问我有什么想法。我首先想到的就是 UIBezierPathCAShapeLayer的方式&#xff0c;为了验证自己的想法&#xff0c;写了一个小 dem…

http响应状态

Servlet API&#xff1a; javax.servlet.http.HttpServletResponse 用于创建HTTP响应&#xff0c;包括HTTP协议的状态行、响应头以及消息体 HTTP状态码&#xff1a; 100-199&#xff1a;表示信息性代码&#xff0c;标示客户端应该采取的其他动作&#xff0c;请求正在进行。 200…

antlr.collections.AST.getLine()I问题的起因及解决

在我们的java web 项目中引入hibernate和struts&#xff0c;当我们使用HQL语句进行查询时会报 antlr.collections.AST.getLine()I的错误&#xff0c;导致程序无法继续运行&#xff0c;这并不是我们的程序写的有错误&#xff0c;出现这个异常的原因是因为我们使用的hibernate和s…

2018湖湘杯海选复赛Writeup

2018湖湘杯Writeup0x01 签到题0x02 MISC Flow0x03 WEB Code Check0x04 WEB Readflag0x05 WEB XmeO0x06 Reverse Replace0x07 MISC Disk0x08 Crypto Common Crypto0x09 Reverse HighwayHash640x10 Web Mynot0x01 签到题 关注合天智汇公众号&#xff0c;回复hxb2018得到flag。0x…

Operation Queues并发编程

并发、异步在我们的编程中&#xff0c;见到的太多了。在iOS中&#xff0c;实现并发的主要三个途径Operation Queues、Dispatch Queues、Dispatch Sources&#xff0c;今天我们就来详细介绍Operatin Queues的使用&#xff0c;花了两天时间写这一篇&#xff0c;值得一看。 为什么…

socket 服务器浏览器与服务器客户端实例

一、服务器与浏览器 // 取得本机的loopback网络地址&#xff0c;即127.0.0.1 IPAddress address IPAddress.Loopback; IPEndPoint endPoint new IPEndPoint(address, 49152); Socket socket new Socket(AddressFamily.InterNetwork, Socke…

匹配3位或4位区号的电话号码,其中区号可以用小括号括起来,也可以不用,区号与本地号间可以用连字号或空格间隔,也可以没有间隔...

public bool IsPhone(string input){string pattern "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$";Regex regex new Regex(pattern);return regex.IsMatch(input);} 转载于:https://www.cnblogs.com/…

Mac MySQL配置环境变量的两种方法

第一种&#xff1a; 1.打开终端,输入&#xff1a; cd ~ 会进入~文件夹 2.然后输入&#xff1a;touch .bash_profile 回车执行后&#xff0c; 3.再输入&#xff1a;open -e .bash_profile 会在TextEdit中打开这个文件&#xff08;如果以前没有配置过环境变量&#xff0c;那么这…

linux之x86裁剪移植---字符界面sdl开发入门

linux下有没有TurboC2.0那样的画点、线、圆的图形函数库&#xff0c;有没有grapihcs.h&#xff0c;或者与之相对应或相似的函数库是什么&#xff1f;有没有DirectX这样的游戏开发库&#xff1f;SDL就是其中之一。SDL&#xff08;Simple DirectMedia Layer&#xff09;是一个夸平…

iOS 视频捕获系列Swift之AVFoundation(一)

iOS 视频捕获系列之AVFoundation(一) AVCaptureMovieFileOutput系列 在iOS开发过程中&#xff0c;或多或少的都涉及视频的操作。 尤其在去年直播行业的带动下&#xff0c;移动端对视频的处理也愈来愈发要求严格。 本文也是在 这篇 中参考而来。 Swift 版本哦&#xff01; 本文 …

C#做外挂常用API

using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; //这个肯定要的 namespace WindowsApplication1 {class win32API{public const int OPEN_PROCESS_ALL 2035711;public const int PAGE_READWRITE 4;public con…