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

用 lint 搭配 DOM 解析,一鍵清掉 Android 專案裡的無用資源

編輯:關於 Android 程式設計

需求一改再改、UI 一調再調,專案裡往往留下一堆再也沒人參照的圖片、版面配置與字串。它們不只是讓 APK 變胖,對接手程式碼的人來說更是無形的負擔。問題是:一個稍具規模的工程,靠人力逐一比對根本不現實,因此我們需要一套自動化的清理流程。

整體策略

整個腳本分成三個階段:

  1. 呼叫 Android Lint 的 --check UnusedResources,把未使用資源的報告輸出成 XML;
  2. 從報告中取出 drawable、layout、anim、menu 等檔案型資源,直接刪除檔案;
  3. 把 res/values 底下未被使用的 color、string、string-array 節點,透過 DOM 節點比對移除,再寫回原檔。

第三步之所以要用 DOM 而不是字串取代,是因為 values 檔案是結構化的 XML,逐行正則替換很容易把格式弄壞;用 DocumentBuilder 解析後再序列化,才不會留下破碎的標籤。

第一步:觸發 lint 並落地報告

public static void doDocCheck(String projectPath, String resultPath)
        throws IOException, InterruptedException {
    String cmd = "cmd /c lint --check UnusedResources " + projectPath
               + " > " + resultPath;
    Process process = Runtime.getRuntime().exec(cmd);
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();
}

第二步:刪除檔案型資源

逐行掃描報告,只挑出帶有 UnusedResources 標記、且排除 appcompat 與 res/values 的行,取冒號前的路徑拼上專案根目錄後刪除。

public static void clearResources(String projectPath, String resultPath)
        throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(resultPath));
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.contains("UnusedResources")
                && !line.contains("appcompat")
                && !line.contains("res\\values")) {
            int end = line.indexOf(':');
            if (end != -1) {
                String f = projectPath + line.substring(0, end);
                new File(f).delete();
            }
        }
    }
}

第三步:用 DOM 移除 values 中的節點

做法是先把報告中涉及的 color、string、string-array 收集成一份「待刪清單」XML,接著解析 res/values 下的每個檔案,逐一比對 name 屬性;一旦命中清單就把該節點從 DOM 樹中移除,最後再序列化寫回檔案。

public static void clear(File clearFile, File checkFile)
        throws ParserConfigurationException, SAXException, IOException {
    Document document = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(clearFile);
    Element rootElement = document.getDocumentElement();
    NodeList childNodes = rootElement.getChildNodes();

    Document document2 = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(checkFile);
    NodeList childNodes2 = document2.getDocumentElement().getChildNodes();

    for (int i = 0; i < childNodes.getLength(); i++) {
        Node childNode = childNodes.item(i);
        if (childNode.getNodeType() != Node.ELEMENT_NODE) continue;
        for (int j = 0; j < childNodes2.getLength(); j++) {
            Node childNode2 = childNodes2.item(j);
            if (childNode2.getNodeType() != Node.ELEMENT_NODE) continue;
            if (childNode.getAttributes().getNamedItem("name").getNodeValue()
                    .equals(childNode2.getAttributes()
                            .getNamedItem("name").getNodeValue())) {
                rootElement.removeChild(childNode);
            }
        }
    }
    writeFile(clearFile.getAbsolutePath(), serialize(rootElement));
}

序列化時需要自己走訪節點樹(遞迴輸出標籤、屬性與文字節點),把結果組回一份格式正確的 XML 字串後覆寫原檔。

使用前請注意

  • 務必先備份或用版控。腳本會直接刪檔,一旦誤刪就得靠 git 找回。
  • lint 判定「未使用」是靜態分析結果,透過反射或動態字串拼出名稱取用的資源可能被誤判,跑完後建議編譯一次並實機走過主要流程。
  • 第三方 aar 帶進來的資源(例如 appcompat)要記得排除,否則容易刪出編譯錯誤。
  • 這份程式碼是臨時性質的工具腳本,正式使用前值得補上 log、dry-run 模式與例外處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved