Android lint删除无用资源文件

本文介绍如何使用Android SDK Tools中的Lint工具清理Android项目中的无用资源,包括手动清理和自动化脚本两种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android项目经过长期的迭代开发,项目当中有大量无用的冗余资源,如果不整理将会导致apk包比较大。

在这里,我使用的是Android sdk tools中自带的Lint工具。


一、直接在Eclipse中使用。

右键需要清理的项目 -> Android Tools -> Run Lint:Check For Common Errors 这时就会打开Lint warning 视图,在这里就可以清理各种无用的资源、代码。

这种方式比较简单,但是需要你自己手动清理,如果项目比较大,就会繁琐无比。

二、Dos下使用命令行。

1,进入Dos,如果没有配置环境变量,那就cd到lint批处理文件所在目录

2,lint --check "UnusedResources" project路径 > 存放路径/result.txt 

使用这行命令,lint会把需要清理的project检索,生成一个结果文件,可以打开这个文件,发现都是一些无用资源的路径信息。

3,解析result结果文件,删除无用资源。

解析的方式就多种多样了,既可以写一个批处理,也可以是exe,当然,最简单的还是写个java类:

private static String encoding = "UTF-8"; // 字符格式  
	private static String projectPath = "";//Android工程所在地址  
	private static String filePath = "";//result的所在路径  
	
	public static void main(String[] args) {
		try {
			init(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void init(boolean autoDelete) throws Exception {
	    File file = new File(filePath, "result.txt");//获取result.txt 文件 生成地址  
	    if (file.isFile() && file.exists()) { // 判断文件是否存在  
	        InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式  
	        BufferedReader bufferedReader = new BufferedReader(read);  
	        String line = null;  
	        while ((line = bufferedReader.readLine()) != null) {
	            if (line.contains("UnusedResources") && !line.contains("res"+File.separator+"value") && !line.contains("appcompat")  
	                    && !line.contains("res"+File.separator+"xml")) {
	                int end = line.indexOf(":");  
	                if (end != -1) {  
	                    String file_end = line.substring(0, end);  
	                    String f = projectPath + file_end;  
	                    System.out.println(f);  
	                    if (autoDelete) {  
	                        new File(f).delete();  
	                        System.out.println("删除成功");  
	                    }  
	                }  
	  
	            }  
	  
	        }  
	        read.close();  
	  
	    }  
	}
这里可以先设置aotoDelete为false,这样执行后只会打印需要删除的资源,检查发现没有问题后,再改为true就会自动删除了。


最后,提供一种更好的解决方法,result文件的生成以及无用资源的删除,都在一个java类中搞定:

public static final String separator = File.separator;

	public static void clearRes(boolean autoDelete, String lintPath,
			String projectPath, String[] dirArray) {
		Process process = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		FileWriter fw = null;
		String cmd = lintPath + " --check UnusedResources " + projectPath;
		int fileCount = 0;
		long fileSize = 0;

		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd-HH-mm-ss");
			Date curDate = new Date(System.currentTimeMillis());
			String dateStr = formatter.format(curDate);
			fw = new FileWriter(projectPath + separator + dateStr + ".txt",
					true);

			Runtime runtime = Runtime.getRuntime();
			String line = null;

			process = runtime.exec(cmd);
			is = process.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);

			while ((line = br.readLine()) != null) {
				for (String dir : dirArray) {
					if (line.startsWith("res" + separator + dir)) {
						int index = line.indexOf(":");
						if (index > 0) {
							String filePath = projectPath + separator
									+ line.substring(0, index);
							if (null != filePath && !"".equalsIgnoreCase(filePath)) {
								filePath = filePath.replaceAll("/", "\\\\");
							}
							++fileCount;
							File file = new File(filePath);
							fileSize += file.length();
							System.out.println("unused file: " + filePath);
							if (autoDelete) {
								boolean success = file.delete();
								System.out.println(filePath + " " + success);
								fw.write(filePath + " " + success + "\n");
								fw.flush();
							}
						}
						break;
					}
				}
			}

			String result = "delete file " + fileCount + ",save space "
					+ fileSize / 1024 + "KB.";
			System.out.println(result);
			fw.write(result);
			fw.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (process != null) {
				process.destroy();
			}
		}
	}

	public static void main(String[] args) {
		if (args.length < 2) {
			System.out
					.println("Please config program arguments. Correct arguments contain both absolute path of lint.bat and that of android project.");
			return;
		}
		String lintPath = args[0];
		String projectPath = args[1];

		String[] dirArray = { "drawable", "layout", "anim", "color" };
		CURes.clearRes(true, lintPath, projectPath, dirArray);
	}

这个程序需要传入两个参数:lint命令路径和工程路径。例如

D:/software/adt-bundle-windows-x86_64/sdk/tools/lint.bat

E:/work_space/myproject

注意lint路径需要把lint.bat也加上,传入路径必须是正斜杠。

(以上代码,都经过验证和使用,完全可以直接运行)


新发现个小问题,eclipse在使用过lint后会出现打包apk失败,这是因为开启了lint的自动检测,

去eclipse  Preferences   选择 Android 下 Lint Error Checking   
去掉勾选项  "Run full error check when exporting app and abort if fatal errors are found "

<think>好的,我现在需要帮助用户解决在Android Studio中删除无用资源的问题。首先,我得回忆一下Android Studio有哪些内置工具或者功能可以帮助用户清理未使用的资源。 用户提到的引用中有引用[1]提到了编辑XML布局文件,这可能和资源管理有关。不过删除无用资源通常不是手动操作,而是通过自动化工具。我记得Android Studio有一个叫做“Remove Unused Resources”的功能,可能是在菜单里的某个地方,比如Refactor或者Analyze菜单下。 然后,我需要考虑步骤是否准确。首先,用户需要打开项目,然后在菜单里找到Analyze > Run Inspection by Name,输入“Unused resources”进行检查。检查完成后,工具会列出未使用的资源,用户可以选择删除。这个过程是否适用于所有资源类型,比如图片、布局、字符串等? 另外,引用[3]提到了动态功能模块,这可能涉及到模块化项目中的资源管理。需要提醒用户在删除资源时注意模块间的依赖关系,避免误删。例如,动态功能模块中的资源可能被基础模块引用,或者通过反射访问,这时候静态分析工具可能检测不到使用情况,导致误报。 还要考虑其他方法,比如使用Lint分析,或者Gradle的shrinkResources选项。引用[3]中的Gradle配置可能相关,因为shrinkResources需要与ProGuard或R8配合使用,在构建时自动移除未使用的资源。需要说明如何在build.gradle文件中启用这些选项,但用户的问题是关于Android Studio的工具,所以可能主要介绍IDE的功能,同时补充Gradle的配置作为优化手段。 可能的问题点:用户是否混淆了删除未使用资源资源缩减?需要明确两者区别。前者是手动或半自动删除,后者是构建时自动处理。同时,需要警告用户备份项目,因为自动工具可能误删某些通过反射引用的资源,比如某些库中的资源或者在代码中动态引用的资源。 总结步骤应该是: 1. 使用Android Studio的Inspection工具检测未使用资源。 2. 检查结果,确认是否确实无用。 3. 删除确认后的资源。 4. 启用shrinkResources作为辅助手段。 5. 注意事项:备份、反射引用、模块依赖。 然后生成相关问题,考虑用户可能进一步想知道如何防止资源冗余,或者处理误删的情况,或者自动化清理的方法。</think>在Android Studio中删除无用资源的方法如下: ### 分步操作指南 1. **使用内置检测工具** - 点击顶部菜单栏的 `Analyze` > `Run Inspection by Name...` - 输入 `Unused resources` 并回车,选择检测范围为整个项目[^1] - 工具会自动扫描所有XML、图片、字符串等资源,并在结果窗口列出未使用的资源 2. **批量删除操作** ```java // 检测结果示例(非代码) Unused resources found: - res/drawable/old_icon.png - res/layout/unused_activity.xml ``` - 在检测结果窗口右键选择 `Safe Delete` 批量删除 3. **启用资源压缩(Gradle配置)** 在模块的 `build.gradle` 中添加: ```groovy android { buildTypes { release { shrinkResources true // 自动移除未使用资源 minifyEnabled true // 需配合ProGuard/R8 } } } ```[^3] ### 注意事项 1. 反射调用的资源会被误判为"未使用",需手动保留 2. 动态功能模块中的资源需检查跨模块引用关系[^3] 3. 建议先执行 `Build > Clean Project` 刷新资源索引
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值