android快速开发--常用utils类

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

完整开源地址:https://docs.qq.com/doc/DSkNLaERkbnFoS0ZF

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import android.content.Context;

  3. import android.util.TypedValue;

  4. /**

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

  6. *

  7. *

  8. *

  9. */

  10. public class DensityUtils

  11. {

  12. private DensityUtils()

  13. {

  14. /* cannot be instantiated */

  15. throw new UnsupportedOperationException(“cannot be instantiated”);

  16. }

  17. /**

  18. * dp转px

  19. *

  20. * @param context

  21. * @param val

  22. * @return

  23. */

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

  25. {

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

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

  28. }

  29. /**

  30. * sp转px

  31. *

  32. * @param context

  33. * @param val

  34. * @return

  35. */

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

  37. {

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

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

  40. }

  41. /**

  42. * px转dp

  43. *

  44. * @param context

  45. * @param pxVal

  46. * @return

  47. */

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

  49. {

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

  51. return (pxVal / scale);

  52. }

  53. /**

  54. * px转sp

  55. *

  56. * @param fontScale

  57. * @param pxVal

  58. * @return

  59. */

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

  61. {

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

  63. }

  64. }

5、SD卡相关辅助类 SDCardUtils

====================================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import java.io.File;

  3. import android.os.Environment;

  4. import android.os.StatFs;

  5. /**

  6. * SD卡相关的辅助类

  7. *

  8. *

  9. *

  10. */

  11. public class SDCardUtils

  12. {

  13. private SDCardUtils()

  14. {

  15. /* cannot be instantiated */

  16. throw new UnsupportedOperationException(“cannot be instantiated”);

  17. }

  18. /**

  19. * 判断SDCard是否可用

  20. *

  21. * @return

  22. */

  23. public static boolean isSDCardEnable()

  24. {

  25. return Environment.getExternalStorageState().equals(

  26. Environment.MEDIA_MOUNTED);

  27. }

  28. /**

  29. * 获取SD卡路径

  30. *

  31. * @return

  32. */

  33. public static String getSDCardPath()

  34. {

  35. return Environment.getExternalStorageDirectory().getAbsolutePath()

  36. + File.separator;

  37. }

  38. /**

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

  40. *

  41. * @return

  42. */

  43. public static long getSDCardAllSize()

  44. {

  45. if (isSDCardEnable())

  46. {

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

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

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

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

  51. long freeBlocks = stat.getAvailableBlocks();

  52. return freeBlocks * availableBlocks;

  53. }

  54. return 0;

  55. }

  56. /**

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

  58. *

  59. * @param filePath

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

  61. */

  62. public static long getFreeBytes(String filePath)

  63. {

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

  65. if (filePath.startsWith(getSDCardPath()))

  66. {

  67. filePath = getSDCardPath();

  68. } else

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

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

  71. }

  72. StatFs stat = new StatFs(filePath);

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

  74. return stat.getBlockSize() * availableBlocks;

  75. }

  76. /**

  77. * 获取系统存储路径

  78. *

  79. * @return

  80. */

  81. public static String getRootDirectoryPath()

  82. {

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

  84. }

  85. }

6、屏幕相关辅助类 ScreenUtils

===================================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import android.app.Activity;

  3. import android.content.Context;

  4. import android.graphics.Bitmap;

  5. import android.graphics.Rect;

  6. import android.util.DisplayMetrics;

  7. import android.view.View;

  8. import android.view.WindowManager;

  9. /**

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

  11. *

  12. *

  13. *

  14. */

  15. public class ScreenUtils

  16. {

  17. private ScreenUtils()

  18. {

  19. /* cannot be instantiated */

  20. throw new UnsupportedOperationException(“cannot be instantiated”);

  21. }

  22. /**

  23. * 获得屏幕高度

  24. *

  25. * @param context

  26. * @return

  27. */

  28. public static int getScreenWidth(Context context)

  29. {

  30. WindowManager wm = (WindowManager) context

  31. .getSystemService(Context.WINDOW_SERVICE);

  32. DisplayMetrics outMetrics = new DisplayMetrics();

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

  34. return outMetrics.widthPixels;

  35. }

  36. /**

  37. * 获得屏幕宽度

  38. *

  39. * @param context

  40. * @return

  41. */

  42. public static int getScreenHeight(Context context)

  43. {

  44. WindowManager wm = (WindowManager) context

  45. .getSystemService(Context.WINDOW_SERVICE);

  46. DisplayMetrics outMetrics = new DisplayMetrics();

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

  48. return outMetrics.heightPixels;

  49. }

  50. /**

  51. * 获得状态栏的高度

  52. *

  53. * @param context

  54. * @return

  55. */

  56. public static int getStatusHeight(Context context)

  57. {

  58. int statusHeight = -1;

  59. try

  60. {

  61. Class<?> clazz = Class.forName(“com.android.internal.R$dimen”);

  62. Object object = clazz.newInstance();

  63. int height = Integer.parseInt(clazz.getField(“status_bar_height”)

  64. .get(object).toString());

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

  66. } catch (Exception e)

  67. {

  68. e.printStackTrace();

  69. }

  70. return statusHeight;

  71. }

  72. /**

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

  74. *

  75. * @param activity

  76. * @return

  77. */

  78. public static Bitmap snapShotWithStatusBar(Activity activity)

  79. {

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

  81. view.setDrawingCacheEnabled(true);

  82. view.buildDrawingCache();

  83. Bitmap bmp = view.getDrawingCache();

  84. int width = getScreenWidth(activity);

  85. int height = getScreenHeight(activity);

  86. Bitmap bp = null;

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

  88. view.destroyDrawingCache();

  89. return bp;

  90. }

  91. /**

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

  93. *

  94. * @param activity

  95. * @return

  96. */

  97. public static Bitmap snapShotWithoutStatusBar(Activity activity)

  98. {

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

  100. view.setDrawingCacheEnabled(true);

  101. view.buildDrawingCache();

  102. Bitmap bmp = view.getDrawingCache();

  103. Rect frame = new Rect();

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

  105. int statusBarHeight = frame.top;

  106. int width = getScreenWidth(activity);

  107. int height = getScreenHeight(activity);

  108. Bitmap bp = null;

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

  110. - statusBarHeight);

  111. view.destroyDrawingCache();

  112. return bp;

  113. }

  114. }

7、App相关辅助类

========================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import android.content.Context;

  3. import android.content.pm.PackageInfo;

  4. import android.content.pm.PackageManager;

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

  6. /**

  7. * 跟App相关的辅助类

  8. *

  9. *

  10. *

  11. */

  12. public class AppUtils

  13. {

  14. private AppUtils()

  15. {

  16. /* cannot be instantiated */

  17. throw new UnsupportedOperationException(“cannot be instantiated”);

  18. }

  19. /**

  20. * 获取应用程序名称

  21. */

  22. public static String getAppName(Context context)

  23. {

  24. try

  25. {

  26. PackageManager packageManager = context.getPackageManager();

  27. PackageInfo packageInfo = packageManager.getPackageInfo(

  28. context.getPackageName(), 0);

  29. int labelRes = packageInfo.applicationInfo.labelRes;

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

  31. } catch (NameNotFoundException e)

  32. {

  33. e.printStackTrace();

  34. }

  35. return null;

  36. }

  37. /**

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

  39. *

  40. * @param context

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

  42. */

  43. public static String getVersionName(Context context)

  44. {

  45. try

  46. {

  47. PackageManager packageManager = context.getPackageManager();

  48. PackageInfo packageInfo = packageManager.getPackageInfo(

  49. context.getPackageName(), 0);

  50. return packageInfo.versionName;

  51. } catch (NameNotFoundException e)

  52. {

  53. e.printStackTrace();

  54. }

  55. return null;

  56. }

  57. }

8、软键盘相关辅助类KeyBoardUtils

=====================================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import android.content.Context;

  3. import android.view.inputmethod.InputMethodManager;

  4. import android.widget.EditText;

  5. /**

  6. * 打开或关闭软键盘

  7. *

  8. * @author zhy

  9. *

  10. */

  11. public class KeyBoardUtils

  12. {

  13. /**

  14. * 打卡软键盘

  15. *

  16. * @param mEditText

  17. *            输入框

  18. * @param mContext

  19. *            上下文

  20. */

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

  22. {

  23. InputMethodManager imm = (InputMethodManager) mContext

  24. .getSystemService(Context.INPUT_METHOD_SERVICE);

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

  26. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,

  27. InputMethodManager.HIDE_IMPLICIT_ONLY);

  28. }

  29. /**

  30. * 关闭软键盘

  31. *

  32. * @param mEditText

  33. *            输入框

  34. * @param mContext

  35. *            上下文

  36. */

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

  38. {

  39. InputMethodManager imm = (InputMethodManager) mContext

  40. .getSystemService(Context.INPUT_METHOD_SERVICE);

  41. imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

  42. }

  43. }

9、网络相关辅助类 NetUtils

================================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import android.app.Activity;

  3. import android.content.ComponentName;

  4. import android.content.Context;

  5. import android.content.Intent;

  6. import android.net.ConnectivityManager;

  7. import android.net.NetworkInfo;

  8. /**

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

  10. *

  11. *

  12. *

  13. */

  14. public class NetUtils

  15. {

  16. private NetUtils()

  17. {

  18. /* cannot be instantiated */

  19. throw new UnsupportedOperationException(“cannot be instantiated”);

  20. }

  21. /**

  22. * 判断网络是否连接

  23. *

  24. * @param context

  25. * @return

  26. */

  27. public static boolean isConnected(Context context)

  28. {

  29. ConnectivityManager connectivity = (ConnectivityManager) context

  30. .getSystemService(Context.CONNECTIVITY_SERVICE);

  31. if (null != connectivity)

  32. {

  33. NetworkInfo info = connectivity.getActiveNetworkInfo();

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

  35. {

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

  37. {

  38. return true;

  39. }

  40. }

  41. }

  42. return false;

  43. }

  44. /**

  45. * 判断是否是wifi连接

  46. */

  47. public static boolean isWifi(Context context)

  48. {

  49. ConnectivityManager cm = (ConnectivityManager) context

  50. .getSystemService(Context.CONNECTIVITY_SERVICE);

  51. if (cm == null)

  52. return false;

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

  54. }

  55. /**

  56. * 打开网络设置界面

  57. */

  58. public static void openSetting(Activity activity)

  59. {

  60. Intent intent = new Intent(“/”);

  61. ComponentName cm = new ComponentName(“com.android.settings”,

  62. “com.android.settings.WirelessSettings”);

  63. intent.setComponent(cm);

  64. intent.setAction(“android.intent.action.VIEW”);

  65. activity.startActivityForResult(intent, 0);

  66. }

  67. }

10、Http相关辅助类 HttpUtils

====================================================================================

[java]  view plain copy 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. package com.zhy.utils;

  2. import java.io.BufferedReader;

  3. import java.io.ByteArrayOutputStream;

  4. import java.io.IOException;

  5. import java.io.InputStream;

  6. import java.io.InputStreamReader;

  7. import java.io.PrintWriter;

  8. import java.net.HttpURLConnection;

  9. import java.net.URL;

  10. /**

  11. * Http请求的工具类

  12. *

  13. * @author zhy

  14. *

  15. */

  16. public class HttpUtils

  17. {

  18. private static final int TIMEOUT_IN_MILLIONS = 5000;

  19. public interface CallBack

  20. {

  21. void onRequestComplete(String result);

  22. }

  23. /**

  24. * 异步的Get请求

  25. *

  26. * @param urlStr

  27. * @param callBack

  28. */

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

  30. {

  31. new Thread()

  32. {

  33. public void run()

  34. {

  35. try

  36. {

  37. String result = doGet(urlStr);

  38. if (callBack != null)

  39. {

  40. callBack.onRequestComplete(result);

  41. }

  42. } catch (Exception e)

  43. {

  44. e.printStackTrace();

  45. }

  46. };

  47. }.start();

  48. }

  49. /**

  50. * 异步的Post请求

  51. * @param urlStr

  52. * @param params

  53. * @param callBack

  54. * @throws Exception

  55. */

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

  57. final CallBack callBack) throws Exception

  58. {

  59. new Thread()

  60. {

  61. public void run()

  62. {

  63. try

  64. {

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

  66. if (callBack != null)

  67. {

  68. callBack.onRequestComplete(result);

  69. }

  70. } catch (Exception e)

  71. {

  72. e.printStackTrace();

  73. }

  74. };

  75. }.start();

  76. }

  77. /**

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

  79. *

  80. * @param urlStr

  81. * @return

  82. * @throws Exception

  83. */

  84. public static String doGet(String urlStr)

  85. {

  86. URL url = null;

  87. HttpURLConnection conn = null;

  88. InputStream is = null;

  89. ByteArrayOutputStream baos = null;

  90. try

  91. {

  92. url = new URL(urlStr);

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

  94. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);

  95. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

  96. conn.setRequestMethod(“GET”);

  97. conn.setRequestProperty(“accept”, “*/*”);

  98. conn.setRequestProperty(“connection”, “Keep-Alive”);

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

  100. {

  101. is = conn.getInputStream();

  102. baos = new ByteArrayOutputStream();

  103. int len = -1;

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

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

  106. {

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

  108. }

  109. baos.flush();

  110. return baos.toString();

  111. } else

  112. {

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

  114. }

  115. } catch (Exception e)

  116. {

  117. e.printStackTrace();

  118. } finally

  119. {

  120. try

  121. {

  122. if (is != null)

  123. is.close();

  124. } catch (IOException e)

  125. {

  126. }

  127. try

  128. {

  129. if (baos != null)

  130. baos.close();

  131. } catch (IOException e)

  132. {

  133. }

  134. conn.disconnect();

  135. }

  136. return null ;

  137. }

  138. /**

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

  140. *

  141. * @param url

  142. *            发送请求的 URL

  143. * @param param

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

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

  146. * @throws Exception

  147. */

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

  149. {

  150. PrintWriter out = null;

  151. BufferedReader in = null;

  152. String result = “”;

  153. try

  154. {

  155. URL realUrl = new URL(url);

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

  157. {

  158. e.printStackTrace();

  159. } finally

  160. {

  161. try

  162. {

  163. if (is != null)

  164. is.close();

  165. } catch (IOException e)

  166. {

  167. }

  168. try

  169. {

  170. if (baos != null)

  171. baos.close();

  172. } catch (IOException e)

  173. {

  174. }

  175. conn.disconnect();

  176. }

  177. return null ;

  178. }

  179. /**

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

  181. *

  182. * @param url

  183. *            发送请求的 URL

  184. * @param param

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

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

  187. * @throws Exception

  188. */

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

  190. {

  191. PrintWriter out = null;

  192. BufferedReader in = null;

  193. String result = “”;

  194. try

  195. {

  196. URL realUrl = new URL(url);

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

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值