Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 常用工具類合集:dp/px 轉換、網絡狀態判斷、GPS 檢測與文件操作

編輯:關於 Android 程式設計

開發 Android 應用的過程中,我們通常會單獨建一個 utils 包,把常用的幫助方法類集中管理。這是一個非常好的習慣:既減少了重複代碼,也讓後續的維護和更新變得輕hess。以下是我日常最常用的幾個工具類,涵蓋 UI 換算、網絡判斷、系統狀態檢測與文件操作。

一、CommonTools:UI 與通用判斷

自定義樣式的 Toast

系統默認 Toast 樣式單調,通過自定義布局可以做出帶圖標、控制位置的提示框。注意 Toast 的顯示必須在主線程調用:

public static void showShortToast(Context context, String message) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.custom_toast, null);
    TextView text = (TextView) view.findViewById(R.id.toast_message);
    text.setText(message);

    Toast toast = new Toast(context);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM, 0, 300);
    toast.setView(view);
    toast.show();
}

dp 與 px 互轉

這是每個 Android 開發者都會寫的方法。核心在於 DisplayMetrics.density,它就是當前屏幕的縮放係數:

/** 根據手機分辨率從 dp 轉成 px */
public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

/** 根據手機的分辨率從 px 轉換成 dp */
public static int px2dip(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}

加 0.5f 是為了做四舍五入,直接強轉會一律向零取整,導致小數值偏小。順帶一提,原版本裡 px2dip 末尾多減了 15,這顯然是調試殘留,實際使用時應去掉。

獲取狀態欄高度

狀態欄高度並沒有公開 API,通常通過反射讀取系統內部資源:

public static int getStatusBarHeight(Context context) {
    int statusBarHeight = 0;
    try {
        Class c = Class.forName("com.android.internal.R$dimen");
        Object obj = c.newInstance();
        java.lang.reflect.Field field = c.getField("status_bar_height");
        int x = Integer.parseInt(field.get(obj).toString());
        statusBarHeight = context.getResources().getDimensionPixelSize(x);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return statusBarHeight;
}

這種做法依賴系統內部實現,在部分定制 ROM 上可能失敗。更穩妥的替代方案是通過 WindowInsets(API 21+)獲取,或者直接讀取一個已加 android:fitsSystemWindows="true" 的 view 的 padding 值。

手機號碼格式校驗

public static boolean isMobileNO(String mobiles) {
    Pattern pattern = Pattern.compile(
            "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
    Matcher matcher = pattern.matcher(mobiles);
    return matcher.matches();
}

需要提醒的是,號段規則會隨運營商放號而不斷變化,硬編碼的正則遲早過時。若非強制要求,用更寬鬆的 ^1\\d{10}$ 反而更省心;真正準確的判斷應該交給服務端運營商接口。

二、NetworkUtils:網絡與定位狀態

網絡是否可用

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    }
    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info != null) {
        for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
    }
    return false;
}

友好的網絡異常提示

public static void networkStateTips(Context context) {
    if (!isNetworkAvailable(context)) {
        CommonTools.showShortToast(context, "網絡故障,請先檢查網絡連接");
    }
}

GPS 是否開啟

public static boolean isGpsEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    List accessibleProviders = locationManager.getProviders(true);
    return accessibleProviders != null && accessibleProviders.size() > 0;
}

getProviders(true) 中的 true 表示只返回已啟用的 provider。若返回列表非空,說明至少有一個定位源可用。

WiFi 是否連接

public static boolean isWifiEnabled(Context context) {
    ConnectivityManager mgrConn = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager mgrTel = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    return ((mgrConn.getActiveNetworkInfo() != null
                && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED)
            || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}

當前網絡類型判斷

區分 WiFi 與移動網絡的標準做法是判斷 NetworkInfo.getType():

/** 判斷當前網絡是否是 WiFi */
public static boolean isWifi(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

/** 判斷當前網絡是否是移動網絡 */
public static boolean is3G(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}

方法名雖叫 is3G,但 TYPE_MOBILE 覆蓋的是全部蜂窩網絡,包括 4G/5G。命名上更準確的做法是 isMobileNetwork。另外,NetworkInfo 這套 API 從 Android 10 起已被標記為 deprecated,新項目應改用 ConnectivityManager.getNetworkCapabilities() 配合 NetworkRequest 回調。

三、FileUtils:文件與存儲操作

路徑常量與文件名校驗

public class FileUtils {
    private final static String t = "FileUtils";

    /** 用於校驗合法的表單文件名 */
    public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";

    // 存儲路徑
    public static final String FORMS_PATH =
            Environment.getExternalStorageDirectory() + "/odk/forms/";
    public static final String INSTANCES_PATH =
            Environment.getExternalStorageDirectory() + "/odk/instances/";
    public static final String CACHE_PATH =
            Environment.getExternalStorageDirectory() + "/odk/.cache/";
    public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";
}

目錄遍歷與創建

public static ArrayList getFoldersAsArrayList(String path) {
    ArrayList mFolderList = new ArrayList();
    File root = new File(path);

    if (!storageReady()) {
        return null;
    }
    if (!root.exists()) {
        if (!createFolder(path)) {
            return null;
        }
    }
    if (root.isDirectory()) {
        File[] children = root.listFiles();
        for (File child : children) {
            if (child.isDirectory()) {
                mFolderList.add(child.getAbsolutePath());
            }
        }
    }
    return mFolderList;
}

public static boolean createFolder(String path) {
    if (storageReady()) {
        boolean made = true;
        File dir = new File(path);
        if (!dir.exists()) {
            made = dir.mkdirs();
        }
        return made;
    }
    return false;
}

public static boolean deleteFolder(String path) {
    // 注意:此實現不是遞歸的
    if (path != null && storageReady()) {
        File dir = new File(path);
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (!file.delete()) {
                    Log.i(t, "Failed to delete " + file);
                }
            }
        }
        return dir.delete();
    }
    return false;
}

public static boolean deleteFile(String path) {
    if (storageReady()) {
        return new File(path).delete();
    }
    return false;
}

deleteFolder() 的注释已明確說明它不是遞歸的,只刪一層。若目錄下還有子目錄,直接刪會失敗。實戰中建議改成遞歸實現,或在 API 16+ 上使用 File.deleteOnExit() 之外的方案。

存儲狀態檢測

public static boolean storageReady() {
    String cardstatus = Environment.getExternalStorageState();
    if (cardstatus.equals(Environment.MEDIA_REMOVED)
            || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
            || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
            || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        return false;
    }
    return true;
}

這個判斷很值得借鑑:它不僅排除「未掛載」,還排除了「只讀掛載」——很多 crashes 正是因為忽視了只讀狀態而寫入失敗。

讀取文件為字節數組

public static byte[] getFileAsBytes(File file) {
    byte[] bytes = null;
    InputStream is = null;
    try {
        is = new FileInputStream(file);

        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            Log.e(t, "File " + file.getName() + " is too large");
            return null;
        }
        bytes = new byte[(int) length];

        int offset = 0;
        int read = 0;
        while (offset < bytes.length && read >= 0) {
            read = is.read(bytes, offset, bytes.length - offset);
            offset += read;
        }

        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        return bytes;
    } catch (FileNotFoundException e) {
        Log.e(t, "Cannot find " + file.getName());
        return null;
    } catch (IOException e) {
        Log.e(t, "Cannot read " + file.getName());
        return null;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

這裡有兩個實戰要點:一是先判斷文件大小是否超過 Integer.MAX_VALUE,否則強轉會溢出;二是用循環 read 而非單次 read,因為 InputStream 的 read 並不保證一次讀完,網絡流尤其明顯。

分塊計算 MD5

public static String getMd5Hash(File file) {
    try {
        // 通過流式分塊讀取,避免一次性加載整個文件到內存
        MessageDigest md = MessageDigest.getInstance("MD5");
        int chunkSize = 256;
        byte[] chunk = new byte[chunkSize];

        long lLength = file.length();
        if (lLength > Integer.MAX_VALUE) {
            Log.e(t, "File " + file.getName() + " is too large");
            return null;
        }
        int length = (int) lLength;

        InputStream is = new FileInputStream(file);
        int l = 0;
        for (l = 0; l + chunkSize < length; l += chunkSize) {
            is.read(chunk, 0, chunkSize);
            md.update(chunk, 0, chunkSize);
        }
        int remaining = length - l;
        if (remaining > 0) {
            is.read(chunk, 0, remaining);
            md.update(chunk, 0, remaining);
        }

        byte[] messageDigest = md.digest();
        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 32) {
            md5 = "0" + md5;
        }
        is.close();
        return md5;
    } catch (NoSuchAlgorithmException e) {
        Log.e("MD5", e.getMessage());
        return null;
    } catch (FileNotFoundException e) {
        Log.e("No Cache File", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Problem reading from file", e.getMessage());
        return null;
    }
}

用 BigInteger 轉十六進制時,高位的前導零會丟失,所以後面用 while 循環補零到 32 位。這個細節漏掉的話,算出的 MD5 有極小概率比標準值短,導致校驗失敗。chunkSize 也可以調大一些,256 字節偏小,實戰中 4KB 到 8KB 更合適。

使用這類工具類的幾點建議

常量的位置。像路徑常量這種東西,建議集中放到 AppConfig 或 Constants 類中,而不是散落在各個 Utils 裡,避免修改時到處找。

注意 API 的新舊。本文中的 ConnectivityManager、NetworkInfo、Environment.getExternalStorageDirectory() 等方式在新版本 Android 上都有更現代化的替代(NetworkCapabilities、App-specific Storage、Scoped Storage)。老代碼可以直接用,新項目則應按當前建議實現,否則在 Android 10 及以上會遇到分區存儲限制。

別忽視異常分支。這些方法幾乎都返回了 null 或 false 作為失敗標記。調用方必須處理這些返回值,否則 null 會一路傳到 UI 層才爆發,排查起來非常痛苦。

這篇會持續更新,陸續把常用到的 util 類補充進來。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved