📌 常用 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、屏幕单位、网络、时间、文件),这些是日常开发里用得最多的。