您的位置:首页 > 移动开发 > Android开发

Android studio 删除无用代码

2016-01-29 18:27 483 查看
max 下需要添加环境变量

环境变量添加 参考这里

1) 工具

1.1) Android lint 在 Android sdk tools 当中 如果可以希望大家能配好环境变量

本文主讲 以命令行形式的删除无效资源的批处理

2) 输入

打开命令行 使用lint命令

如图:

lint --check "UnusedResources" /Users/baozi/Dev/android/android > result.txt


/Users/baozi/Dev/android/android为工程路径

/User/baozi/result.txt 为输出txt路径

在命令行中输入: /Users/baozi/Dev/android/android > /User/baozi/result.txt

生成的扫描结果将会存放在当前目录下的 result.txt 当中

如我的目录 /Users/baozi/result.txt

3) 输出文件result.txt

打开文件目录 /Users/baozi/result.txt 重点内容

4) 根据结果 批量删除对应的文件

本文重点 当你第一次运行时 发现需要数千资源文件需要删除的时候就会伤脑筋

手工逐条删除 并不符合程序猿三大优秀品质 : 懒惰 没有耐心 骄傲

尝试过使用 vim 删除 发现操作起来也相当麻烦

大家可以参考下面的代码 使用FIle 获取 result.txt 中的文件信息 调用 File .delete(); 方法删除

/**
* 删除 未使用的冗余资源(图片 xml布局)
*
* @param b
*
*            false 显示资源列表
*
*            true 显示资源列表 并删除资源
*
* @throws Exception
*/
private static void init(boolean b) throws Exception {

String encoding = "UTF-8"; // 字符格式
String projectPath = "/Users/baozi/Dev/shihui/android/";//Android工程所在地址
String filePath1 = "/Users/baozi";//result的所在路径
File file = new File(filePath1, "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/value") && !line.contains("appcompat")
&& !line.contains("res/xml")) {
// System.out.println(line);
int end = line.indexOf(":");
if (end != -1) {
String file_end = line.substring(0, end);
String f = projectPath + file_end;
System.out.println(f);
if (b) {
new File(f).delete();
System.out.println("删除成功");
}
}

}

}
read.close();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: