首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Android 開發常用 19 大工具類匯總:HttpUtils、FileUtils、TimeUtils 等

     編輯:PHP 綜合知識

專案簡介

TrineaAndroidCommon 是一個整理了 Android 開發中高頻工具類的開源庫,大部分同樣適用於純 Java 專案。原始碼託管於 GitHub,支援直接作為 Library 依賴或按需複製代碼。

19 大工具類一覽

工具類核心功能代表方法
HttpUtilsHTTP 請求封裝,支援 GET/POST、參數配置、GZIP、緩衝讀取httpGet(url), httpPost(url, params), httpGetString(url)
DownloadManagerPro系統 DownloadManager 增強,查詢進度、狀態、錯誤碼、檔案路徑getStatusById(id), getDownloadBytes(id), getFileName(id)
ShellUtilsShell 命令執行,Root 權限檢查、靜默安裝 APKcheckRootPermission(), execCommand(cmd, isRoot)
PackageUtils應用安裝/解除安裝、系統應用判斷、Root 靜默操作install(ctx, apkPath), uninstall(ctx, pkg), isSystemApplication(ctx, pkg)
PreferencesUtilsSharedPreferences 讀寫封裝,支援 String/Int/Boolean/Float/Long/SetputString(ctx, key, val), getString(ctx, key)
JSONUtilsJSON 物件安全取值,預設值回退getString(json, key, def), getMap(json, key)
FileUtils檔案讀寫、大小、刪除、複製、MD5、MIME 類型readFile(path), writeFile(path, content, append), getFileSize(path)
ResourceUtils從 assets/raw 讀取資源檔內容geFileFromAssets(ctx, fileName), geFileFromRaw(ctx, resId)
StringUtils常用字串判斷、編碼、首字母大寫、截斷isEmpty(str), isBlank(str), utf8Encode(str), capitalizeFirstLetter(str)
ParcelUtilsParcel 讀寫 Boolean、Map、List 等特殊類型readBoolean(parcel), writeHashMap(map, parcel)
RandomUtils隨機字串、數字、顏色、UUIDgetRandom(chars, len), getRandomNumbers(len)
ArrayUtils陣列判空、取前後元素、循環取值isEmpty(arr), getNext(arr, val, def, circle)
ImageUtilsBitmap/Drawable/ByteArray 互轉、縮放bitmapToDrawable(bmp), scaleImage(bmp, sw, sh)
ListUtilsList 判空、Join、去重添加isEmpty(list), join(list, sep), addDistinctEntry(list, entry)
MapUtilsMap 判空、字串解析為 Map、Map 轉 JSONisEmpty(map), parseKeyAndValueToMap(str, ...), toJson(map)
ObjectUtils物件比較、轉換(Integer[] ↔ int[])isEquals(a, b), compare(v1, v2), transformIntArray(arr)
SerializeUtils物件序列化到檔案、反序列化serialization(path, obj), deserialization(path)
SystemUtils系統資訊:建議執行緒池大小getDefaultThreadPoolSize()
TimeUtils時間格式化、當前時間戳、相對時間getCurrentTimeInLong(), getTime(millis, format)

接入方式

// build.gradle
dependencies {
    implementation 'com.trinea.android:common:4.2.0' // 具體版本請查 Maven Central
}
// 或複製源碼到專案 module

使用範例

// HttpUtils
String html = HttpUtils.httpGetString("https://api.example.com/data");

// FileUtils
String json = FileUtils.readFile("/sdcard/config.json");
FileUtils.writeFile("/sdcard/log.txt", "new line\n", true);

// TimeUtils
String now = TimeUtils.getTime(System.currentTimeMillis(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

// StringUtils
if (StringUtils.isBlank(input)) { ... }
String encoded = StringUtils.utf8Encode("中文");

優勢與注意

  • 零依賴:僅依賴 Android SDK / Java 標準庫。
  • 單元測試覆蓋:核心方法均有測試用例。
  • API 穩定:長期維護,版本升級極少破壞性變更。
  • 注意:部分方法(如 ShellUtils.execCommand)涉及 Root,需在具備權限的設備上運行;生產環境謹慎使用。

總結

TrineaAndroidCommon 將 Android 開發中分散在各專案的「工具方法」標準化、模組化,極大減少重複造輪子。建議團隊專案統一引入,並根據業務需求擴充自有工具類。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved