編輯:關於 Android 程式設計
在日常開發裡,有些功能幾乎每個專案都會用到。把這些常見的程式碼片段整理成自己的工具類,能省下大量重複打字的时间。以下整理了十個實作中出現頻率相當高的程式碼片段,值得收進你的工具箱。
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
public static boolean isActiveNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null && info.isAvailable();
}
// B 轉 KB
public static double transB2KB(long b) {
return b / 1024;
}
// KB 轉 MB
public static double transKB2M(double kb) {
return kb / 1024;
}
public static void checkFileDirectory(String path) {
if (path != null) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
public static Long getTotalSize(String url) {
try {
return NetworkUtil.getContentSize(url);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
public static void showNetException(Context context) {
Toast.makeText(context,
context.getResources().getString(R.string.net_exception),
Toast.LENGTH_SHORT).show();
}
public static long transDayToTime(long days) {
return days * 24 * 60 * 60 * 1000;
}
public static int transTimeToDay(long time) {
return (int) (time / (24 * 60 * 60 * 1000));
}
public static boolean isSystemApplication(Context context, String packageName) {
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo info = pm.getApplicationInfo(
packageName, PackageManager.GET_META_DATA);
return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
} catch (Exception e) {
Log.i("xxxxx", "Exception ");
}
return false;
}
public static boolean isNull(String str) {
if (str != null) {
str = str.trim();
if (str.length() != 0) {
return false;
}
}
return true;
}
這些片段看似零散,卻幾乎 ubiquitous 地出現在每個專案裡。把它們集中管理成一個 Utils 類別,不僅讓程式碼更乾淨,也能在團隊之間形成一致的開發風格。
APK 反編譯入門:圖片、XML 與代碼資源的提取流程
瞭解 APK 的內部結構,對排查問題、學習他人實現思路、驗證自己應用的加固效果都很有幫助。本文梳理一下提取 APK 中三類資源的基本流程:圖片資源、XML 資源和代碼資源
用 LoaderManager 讀取聯絡人電話,順手解決游標洩漏
事情是這樣的:隊長要我把「叫出系統通訊錄、選人、把電話號碼帶回 UI」這件事封裝成一個工具類,直接呼叫就能用。於是故事開始了…… 第一版:直白的寫法 先寫一個靜態類,提
RecyclerView 瀑布流實作:StaggeredGridLayoutManager 與 ItemDecoration
瀑布流的實現核心 RecyclerView 實作瀑布流,關鍵在於 StaggeredGridLayoutManager。它能讓不同高度的項目錯位排列,形成視覺上的瀑布流效
Android 仿社群貼子的 SpannableString 解析技巧
在新浪微博、QQ 空間等社群場景中,貼文常包含話題、表情與好友提及。這類內容通常不是單純文字,而是需要局部變色、可點擊或替換成圖片。Android 中常使用 Spanna