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

清理 Android 工程無用資源的兩種做法

編輯:關於 Android 程式設計

項目迭代久了,res 目錄裡會積攢大量再無人引用的圖片、佈局和字符串,白白佔著包體積。手動排查顯然不現實,好在 Android SDK 自帶的 lint 工具就能勝任這件事。

方法一:用 lint 掃描未使用資源並導出清單

執行命令:

lint –check "UnusedResources" [project_path] > result.txt

跑完之後,當前目錄下會生成一份 result.txt 清單,內容大致如下:

每一行記錄了資源文件的路徑和未使用的具體位置。資源多的時候,清單可能長達幾百行,靠眼睛一條條刪顯然不現實。

方法二:寫腳本批量刪除

既然清單格式固定,就乾脆寫個小工具解析它,把對應文件批量刪掉:

 public class DelAction { public static void main(String[] args) throws IOException { String projectPath = "***"; BufferedReader reader = new BufferedReader(new FileReader("result路徑")); String line; int count = 0; while ((line = reader.readLine()) != null) { if (line.contains("UnusedResources") && !line.contains("res/value") && !line.contains("appcompat")) { count++; int end = line.indexOf(":"); if (end != -1) { String file = line.substring(0, end); String f = projectPath + file; boolean flag = new File("【拼出文件完整路徑】" + f.replace("***", "")).delete(); System.out.println("【拼出文件完整路徑】" + f + "=>del=>" + flag); } } } } }

腳本裡那幾個 contains 的排除條件是關鍵:res/value 下的內容(如 colors、strings)不能簡單按文件刪,appcompat 相關資源則是支持庫的,動不得。路徑拼接部分需要按自己工程的目錄結構調整,把佔位符替換成實際值。

最後一點提醒:刪完之後一定要重新執行一次 lint 掃描。因為某張圖片可能同時被多處引用,第一輪刪除後,原本「被使用」的資源可能變成新的無用資源,往往需要重複幾輪才能真正清理乾淨。刪除前記得先提交一次代碼,留出回退餘地。

以上就是本文的全部內容,希望對大家的學習有所幫助。

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