Clear unused resources in the Android Project

Source: Internet
Author: User

The project needs to be changed and the UI needs to be adjusted. The result is that a bunch of junk Resources in the project that are not used but are not cleaned up, not to mention the project size, for new project users or those who read code from other modules, these uncleared resources may also cause problems. Therefore, it is best to clear the garbage, for a slightly larger project, manual cleanup is obviously unrealistic. This requires a method to do these tasks.

Clear resource files

To clear useless resources, find them first. We know that Anroid SDK has a tool calledLintTo help us check the problems in the project. One of the functions is to find resources that are useless. This step is simple and you can directly execute the following commands on the project to be cleaned up:

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

After the preceding commands are executedUnusedResourcesAll problems are savedResult.txtNow, let's take a look.Result.txtContent

res/values/arrays.xml:202: Warning: The resource R.array.msg_my_friend_category_items appears to be unused [UnusedResources]    <string-array name="msg_my_friend_category_items">^M                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~res/layout/back_up_level_list.xml: Warning: The resource R.layout.back_up_level_list appears to be unused [UnusedResources]res/layout/backup_list.xml: Warning: The resource R.layout.backup_list appears to be unused [UnusedResources]res/layout/backup_listview_item.xml: Warning: The resource R.layout.backup_listview_item appears to be unused [UnusedResources]

The layout and values that are useless are listed. With this information, what needs to be done next is to analyze this information. manual analysis is not realistic, because this file may be very large. For example, after I execute the above command, there will be 2212 lines of files, of course, this kind of thing is handled by the computer.

After carefully reading the content in the generated text, we will find that the results are output by line. Each problem is a separate line, and the content in each line is also regular.

File_path [: line]: Warning: info [UnusedResources}

So we can easily find out which file or even which line has a problem. During my processing, I only cleared useless files, such as res/values/arrays. xml: 202. Let's see how to clear useless resource files.

String projectPath = "***";BufferedReader reader = new BufferedReader(new FileReader("/home/angeldevil/result.txt"));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;            System.out.println(f);            new File(f).delete();        }    }}

The program is very simple, just a few lines of code, that is, readingResult.txtEach row of the file filters out the rows that do not need to be processed based on the conditions you need (for example, I only want to clean up anim, drawable, and layout, so the information in the res/value directory is filtered out, and ignore the appcompat information), each line ":" The Front string is the file name. If you find the file name, you can simply delete it or print it out, or write it to a file to confirm whether to delete it again. After writing the result to a file, we can check whether the file is useless but still does not want to delete it, if yes, the processing method is also very simple. Remove this line or simply make a mark, such as hitting # in front, and then read the file to delete the file corresponding to the row not marked.

It looks simple, but there are several points to note:

Clear Java files

First, we need to find the files that are not used, or use tools. I use UCDetector, that is, Unused Code Detector. If you do not use this tool, Google it directly.

Install EclipseUCDetectorPlug-ins that perform a check on the project. This may take a long time. I checked it for two hours .. Like lint, the result will be output to a text file, which is also a line for each problem, so you only need to analyze the line, for example:

com.**.SampleAdapter.<init>(SampleAdapter.java:18)  Class "SampleAdapter" has 0 references        SampleAdapter org.ucdetector.analyzeMarkerReferencecom.**.SampleAdapter.<init>(SampleAdapter.java:56)  Change visibility of Member class "SampleAdapter.ViewHolder" to private - May cause compile errors!   SampleAdapter.ViewHolder      org.ucdetector.analyzeMarkerVisibilityPrivate

As you can see, the detection results contain a lot of information, such as a class is not used, the visibility of a method is too large, and so on. Similarly, only useless class files are processed.

String reportPath = "**/ucdetector_reports/UCDetectorReport_001.txt";BufferedReader reader = new BufferedReader(new FileReader(reportPath));String line;int count = 0;while((line = reader.readLine()) != null) {    if (line.contains("Class") && line.contains("has 0 references") && !line.contains("Method")[ && other conditions]) {        count++;        int end = line.indexOf(".<init>");        if (end != -1){            String className = line.substring(0, end);            System.out.println(className);        }    }}

The above code basically finds useless classes. We recommend that you output the results instead of directly deleting them, after the result is output, you will find that you do not want to delete many files, such:

com.nostra13.universalimageloader.core.assist.DiscCacheUtil.<init>(DiscCacheUtil.java:31)       Class "DiscCacheUtil" has 0 references  DiscCacheUtil   org.ucdetector.analyzeMarkerReference   Sergey Tarasevich (nostra13[at]gmail[dot]com)

Files in some class libraries may also be detected.IfFilter out the conditions. Some of your files may not be used for the moment but you do not want to delete them. You can filter out the results.

Summary

There are two steps to clean up resources:

PassUCDetectorAndLintBasically, the project can be detected.UnusedResourceRelated problems, such as method visibility. A method does not use this problem. If you do not need to handle it, You can manually handle it when you change it to the corresponding file, the main process is that some files or classes are not used. Check the report and analyze the report. This type of report generally reports a problem on each line, and the text on each line is regular (the tool must generate a regular report). Just filter out the information we need according to the regular rule.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.