Android 開發中重複造輪子不僅浪費時間,還易引入 Bug。本文匯總 19 大類、100+ 實用工具類,涵蓋網絡、文件、圖片、集合、系統、時間、隨機、序列化等高頻場景,代碼托管於 TrineaAndroidCommon,可直接作為 Library 依賴或按需複製。
| # | 工具類 | 核心功能 |
|---|---|---|
| 1 | HttpUtils | HTTP GET/POST、參數構建、GZIP、緩存控制、響應解析 |
| 2 | DownloadManagerPro | 系統下載管理增強:進度、狀態、失敗原因、文件路徑查詢 |
| 3 | ShellUtils | Root 權限檢查、Shell 命令執行(同步/異步、結果捕獲) |
| 4 | PackageUtils | 安裝/卸載應用(靜默/普通)、判斷系統應用、獲取版本信息 |
| 5 | PreferencesUtils | SharedPreferences 讀寫封裝:String/Int/Boolean/Float/Long/Set |
| 6 | JSONUtils | JSON 解析/構建:安全獲取 String/Int/Boolean/JSONArray/JSONObject/Map |
| 7 | FileUtils | 文件讀寫、複製/移動/刪除、大小獲取、MD5、MIME 類型判斷 |
| 8 | ResourceUtils | 讀取 assets/raw 目錄文件、資源 ID 獲取 |
| 9 | StringUtils | 空判斷、首字母大寫、UTF-8 編碼、截取、分割、正則匹配 |
| 10 | ParcelUtils | Parcel 讀寫 Boolean/Map/List/SparseArray 等特殊類型 |
| 11 | RandomUtils | 隨機字符串、數字、顏色、UUID、高斯分佈 |
| 12 | ArrayUtils | 空判斷、獲取前後元素(循環/非循環)、翻轉、去重 |
| 13 | ImageUtils | Bitmap↔Drawable↔Byte[] 轉換、縮放、圓角、灰度、模糊 |
| 14 | ListUtils | 空判斷、Join 分割、添加不重複元素、分頁、打亂 |
| 15 | MapUtils | 空判斷、字符串解析為 Map、Map 轉 JSON、鍵值交換 |
| 16 | ObjectUtils | 對象比較、深拷貝、屬性複製、toString 生成 |
| 17 | SerializeUtils | 對象序列化/反序列化(文件/字節數組/SharedPreferences) |
| 18 | SystemUtils | 設備信息、屏幕尺寸、SD卡狀態、網絡類型、應用版本、Root 狀態 |
| 19 | TimeUtils | 時間格式化、解析、相對時間(剛剛/幾分鐘前)、時區、倒計時 |
// Gradle (JitPack)
allprojects { repositories { maven { url 'https://jitpack.io' } } }
dependencies {
implementation 'com.github.Trinea:TrineaAndroidCommon:latest.release'
}
// 或 Maven Central (若已發布)
// implementation 'cn.trinea.android.common:trinea-android-common:x.y.z'
String html = HttpUtils.httpGetString("https://api.example.com/data");
// 或進階配置
HttpRequest request = new HttpRequest("https://api.example.com/data")
.setConnectTimeout(10000)
.setReadTimeout(20000)
.addHeader("Authorization", "Bearer " + token);
HttpResponse response = HttpUtils.httpGet(request);
if (response.isSuccess()) {
String body = response.getBody();
long expire = response.getExpireTime(); // 緩存過期時間
}
String content = FileUtils.readFile("/sdcard/config.txt");
FileUtils.writeFile("/sdcard/log.txt", "新日誌\n", true); // 追加模式
long size = FileUtils.getFileSize("/sdcard/video.mp4");
FileUtils.deleteFile("/sdcard/temp.cache");
String ago = TimeUtils.getRelativeTimeSpanString(System.currentTimeMillis() - 3600000);
// 輸出:"1小時前"
Bitmap scaled = ImageUtils.scaleImage(originalBitmap, 0.5f, 0.5f);
Drawable drawable = ImageUtils.bitmapToDrawable(scaled);
byte[] bytes = ImageUtils.drawableToByte(drawable);
| 庫 | 優勢 | 適用場景 |
|---|---|---|
| TrineaAndroidCommon | 輕量、全面、純原生、文檔完善 | 不想引入大型框架、需精細控制的項目 |
| AndroidX Core/KTX | 官方維護、擴展函數豐富 | 現代 Android 開發首選基礎庫 |
| Apache Commons Lang/IO | 成熟穩定、功能極全 | Java 後端/跨平台模塊共用代碼 |
| Google Guava | 集合、緩存、並發工具極強 | 複雜業務邏輯、服務端開發 |
TrineaAndroidCommon 專為 Android 客戶端場景打磨,解決了「小功能不想引大庫、大庫又用不上大部分功能」的痛點,是 Android 開發者工具箱中的利器。