当前位置: 首页 > news >正文

【大前端】常用 Android 工具类整理


📌 常用 Android 工具类整理

1. 日志与调试

  • LogUtils
    封装系统 Log,支持统一 TAG、开关控制、日志文件存储。

  • CrashHandler
    全局捕获异常,保存到文件或上报服务器。


2. UI 与显示

  • ToastUtils
    封装 Toast,支持全局 Context、安全线程调用。

  • SnackbarUtils
    方便调用带 Action 的 Snackbar。

  • DensityUtils
    px/dp/sp 转换、屏幕宽高获取。

  • KeyboardUtils
    显示/隐藏软键盘、判断键盘是否弹出。

  • StatusBarUtils
    设置沉浸式状态栏、修改状态栏字体颜色。


3. 设备信息

  • DeviceUtils
    获取设备 ID、系统版本、厂商型号、IMEI/AndroidID。

  • AppUtils
    获取 App 版本号、包名、签名校验、跳转应用市场。

  • NetworkUtils
    判断网络是否可用、WiFi/移动网络、获取 IP 地址。

  • BatteryUtils
    电量、充电状态。


4. 存储与文件

  • FileUtils
    文件读写、删除、复制、大小计算。

  • SPUtils
    SharedPreferences 封装,支持存储任意对象(Gson/JSON)。

  • CacheUtils
    磁盘缓存、内存缓存。

  • PathUtils
    获取内置存储、外部存储路径,App 缓存路径。


5. 时间与日期

  • TimeUtils
    时间戳转换、格式化、获取当前时间。

  • DateUtils
    日期计算:天数差、周几、月份。


6. 正则与校验

  • RegexUtils
    手机号、邮箱、身份证、URL、IP 等验证。

  • StringUtils
    判空、反转、截取、大小写转换、MD5/SHA 加密。


7. 线程与任务

  • ThreadUtils
    快速切换主线程/子线程执行。

  • ExecutorUtils
    封装线程池,任务调度。


8. 图像与媒体

  • ImageUtils
    Bitmap 与 Drawable 转换、缩放、压缩、圆角/圆形处理。

  • ScreenShotUtils
    截屏、保存到相册。

  • VideoUtils
    获取视频缩略图、时长。


9. 系统功能调用

  • IntentUtils
    快速调用系统功能:打电话、发短信、打开相机、浏览器。

  • ClipboardUtils
    复制/粘贴文本。

  • NotificationUtils
    通知栏管理。

  • VibratorUtils
    控制震动。


10. 安全与加密

  • EncryptUtils
    MD5、SHA、Base64、AES、RSA。

  • SignUtils
    签名校验、接口加密。


📚 推荐开源工具类库

如果不想自己封装,可以直接使用一些成熟的工具库:

  • AndroidUtilCode → Blankj 大佬维护的工具类合集,几乎涵盖所有场景。

  • Guava (Google) → 集合、缓存、并发工具。

  • Apache Commons → 字符串、IO 工具。


📌 1. 日志工具类 LogUtils

package com.example.utils;import android.util.Log;public class LogUtils {private static final String TAG = "AppLog";private static boolean isDebug = true; // 控制日志开关public static void setDebug(boolean debug) {isDebug = debug;}public static void d(String msg) {if (isDebug) Log.d(TAG, msg);}public static void i(String msg) {if (isDebug) Log.i(TAG, msg);}public static void w(String msg) {if (isDebug) Log.w(TAG, msg);}public static void e(String msg) {if (isDebug) Log.e(TAG, msg);}
}

📌 2. Toast 工具类 ToastUtils

package com.example.utils;import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;public class ToastUtils {private static Toast toast;private static final Handler handler = new Handler(Looper.getMainLooper());public static void show(final Context context, final String msg) {handler.post(() -> {if (toast != null) {toast.cancel();}toast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);toast.show();});}
}

📌 3. SharedPreferences 工具类 SPUtils

package com.example.utils;import android.content.Context;
import android.content.SharedPreferences;public class SPUtils {private static final String FILE_NAME = "app_prefs";public static void put(Context context, String key, String value) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);sp.edit().putString(key, value).apply();}public static String get(Context context, String key, String defValue) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);return sp.getString(key, defValue);}public static void remove(Context context, String key) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);sp.edit().remove(key).apply();}public static void clear(Context context) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);sp.edit().clear().apply();}
}

📌 4. 屏幕尺寸/单位转换 DensityUtils

package com.example.utils;import android.content.Context;
import android.util.DisplayMetrics;public class DensityUtils {public static int dp2px(Context context, float dp) {DisplayMetrics metrics = context.getResources().getDisplayMetrics();return (int) (dp * metrics.density + 0.5f);}public static int px2dp(Context context, float px) {DisplayMetrics metrics = context.getResources().getDisplayMetrics();return (int) (px / metrics.density + 0.5f);}public static int sp2px(Context context, float sp) {DisplayMetrics metrics = context.getResources().getDisplayMetrics();return (int) (sp * metrics.scaledDensity + 0.5f);}public static int px2sp(Context context, float px) {DisplayMetrics metrics = context.getResources().getDisplayMetrics();return (int) (px / metrics.scaledDensity + 0.5f);}
}

📌 5. 网络状态工具类 NetworkUtils

package com.example.utils;import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;public class NetworkUtils {public static boolean isConnected(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm != null) {NetworkInfo info = cm.getActiveNetworkInfo();return info != null && info.isConnected();}return false;}public static boolean isWifi(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm != null) {NetworkInfo info = cm.getActiveNetworkInfo();return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;}return false;}
}

📌 6. 时间工具类 TimeUtils

package com.example.utils;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;public class TimeUtils {public static String getNowTime(String format) {return new SimpleDateFormat(format, Locale.getDefault()).format(new Date());}public static String millis2String(long millis, String format) {return new SimpleDateFormat(format, Locale.getDefault()).format(new Date(millis));}public static long string2Millis(String time, String format) {try {return new SimpleDateFormat(format, Locale.getDefault()).parse(time).getTime();} catch (Exception e) {return -1;}}
}

📌 7. 文件工具类 FileUtils

package com.example.utils;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileUtils {public static boolean copy(File src, File dest) {try {FileInputStream fis = new FileInputStream(src);FileOutputStream fos = new FileOutputStream(dest);byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}fis.close();fos.close();return true;} catch (IOException e) {return false;}}public static boolean delete(File file) {if (file.isDirectory()) {for (File child : file.listFiles()) {delete(child);}}return file.delete();}public static long getFileSize(File file) {if (!file.exists()) return 0;if (file.isFile()) return file.length();long size = 0;for (File f : file.listFiles()) {size += getFileSize(f);}return size;}
}

⚡ 这里写了 7 个常用工具类(日志、Toast、SP、屏幕单位、网络、时间、文件),这些是日常开发里用得最多的。


文章转载自:

http://5HUDK803.bppmL.cn
http://ftEXM6Ok.bppmL.cn
http://zorOnghO.bppmL.cn
http://uxL9cpV8.bppmL.cn
http://XzzThUN9.bppmL.cn
http://o0f7tPUK.bppmL.cn
http://Yaan86Ea.bppmL.cn
http://klkqEMxH.bppmL.cn
http://I5Pj9f0r.bppmL.cn
http://u3SdrBWM.bppmL.cn
http://Q4cXaZcF.bppmL.cn
http://wXDFBbLH.bppmL.cn
http://oHRhQeMU.bppmL.cn
http://oYgiNVOz.bppmL.cn
http://HaTr8HdS.bppmL.cn
http://pkC8AMQT.bppmL.cn
http://ffrqDqYh.bppmL.cn
http://Vmr1utM4.bppmL.cn
http://0ASNpTH9.bppmL.cn
http://WdkDHA4v.bppmL.cn
http://mBopI3qB.bppmL.cn
http://WVJy8iOz.bppmL.cn
http://QsJxI8Uc.bppmL.cn
http://rJqgtaXE.bppmL.cn
http://lV96RRPY.bppmL.cn
http://ZDLmXjkz.bppmL.cn
http://SJxApKja.bppmL.cn
http://UGL5mnCB.bppmL.cn
http://MCHzBdvP.bppmL.cn
http://8C8TgiWp.bppmL.cn
http://www.dtcms.com/a/377911.html

相关文章:

  • Gradle Task的理解和实战使用
  • 强大的鸿蒙HarmonyOS网络调试工具PageSpy 介绍及使用
  • C++/QT 1
  • 软件测试用例详解
  • 【ROS2】基础概念-进阶篇
  • 三甲地市级医院数据仓湖数智化建设路径与编程工具选型研究(上)
  • 利用Rancher平台搭建Swarm集群
  • BRepMesh_IncrementalMesh 重构生效问题
  • VRRP 多节点工作原理
  • 运行 Ux_Host_HUB_HID_MSC 通过 Hub 连接 U 盘读写不稳定问题分析 LAT1511
  • Oracle体系结构-控制文件(Control Files)
  • 0303 【软考高项】项目管理概述 - 组织系统(项目型组织、职能型组织、矩阵型组织)
  • Spark-SQL任务提交方式
  • 10、向量与矩阵基础 - 深度学习的数学语言
  • 开发避坑指南(45):Java Stream 求两个List的元素交集
  • React19 中的交互操作
  • 阿里云ECS vs 腾讯云CVM:2核4G服务器性能实测对比 (2025)
  • 网络编程;TCP多进程并发服务器;TCP多线程并发服务器;TCP网络聊天室和UDP网络聊天室;后面两个还没写出来;0911
  • STM32项目分享:基于stm32的室内环境监测装置设计与实现
  • 利用归并算法对链表进行排序
  • GPU 服务器压力测试核心工具全解析:gpu-burn、cpu-burn 与 CUDA Samples
  • Power Automate List Rows使用Fetchxml查询的一个bug
  • Zynq开发实践(FPGA之ddr sdram读写)
  • LeetCode 热题 160.相交链表(双指针)
  • 西门子 S7-200 SMART PLC 编程:转换 / 定时器 / 计数器指令详解 + 实战案例(案例篇)
  • SAM-Med3D:面向三维医疗体数据的通用分割模型(文献精读)
  • 考研复习-计算机网络-第五章-传输层
  • win11安装jdk8-u211-windows
  • 从传统到智能:3D 建模流程的演进与 AI 趋势 —— 以 Blender 为例
  • 开发避坑指南(46):Java Stream 对List的BigDecimal字段进行求和