Remove unused resources from Android projects

Source: Internet
Author: User

The project needs to change again, the UI a tune again, the result is a bunch of items in the project has not been used but not clean up the garbage resources, not to mention the project size problem, for the new entry of the person or look at the code of other modules, these clean resources may also be troubled, so it is best to clean up the rubbish, For a slightly larger project, manual cleanup is obviously unrealistic, which requires a way to do these things.

Clean Up resource files

To clean up useless resources, the first thing to do is to find them, and we know that the Anroid SDK has a tool called lintthat can help us look at problems in the project, one of which is to find useless resources, so this is a simple step, Execute the following command directly on the project that needs to be cleaned:

?

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

After the execution of the above command after the project about the unusedresources of the problem is saved to Result.txt , first look at the contents of Result.txt

?

1 2 3 4 5 6 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]

You can see information such as the unused layout and values that are useless. With this information, the next thing to do is to analyze this information, manual analysis is not very realistic, because this file can be very large, such as I executed the above command after the file has 2212 lines, this kind of thing, of course, to the computer to solve.

Looking closely at the content in the generated text will find that the results are output by row, each problem is a separate line, and the contents of each row are very regular

File_path[:line]: warning:info [Unusedresources}

So it is easy to get which file or even which line has a problem, I deal with the time only clean up the useless files, like the above res/values/arrays.xml:202 there is no tube, see below how to clean up the unused resource files.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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, is to read every line of the result.txt file, according to their own requirements to filter out the rows do not need to process (for example, I just want to clean anim, drawable and layout, so filter out res/ Value directory information, and ignore AppCompat related information), each line ":" Before the string is the file name, found the file name is good to handle, directly delete, or print out, or write to a file to confirm the confirmation to delete, When the results are written to a file, we can see if the file is now useless but still do not want to delete the file, if so, the processing method is very simple, remove this line or simply make a mark, such as the previous #, and then read the file to do not mark the row corresponding file deleted.

It looks simple, but there are a few things to note:

    1. Some layout files may have been used by you before, and in the corresponding Java file, use the ID in the layout layouts, such as the Onclicklistener for some ID controls, and the IDs in the onclick switch...case. But finally do not use this layout, this layout is Unusedresource, but previously referenced in Java code in the layout of some of the ID of the reference has not been cleared, at this time to delete this layout will be an error, You can choose to clean up the Java code for the error because they are actually dead code. or each time you clean up a portion of the resource files, such as cleaning up layout, and then clean up the drawable, for each item can also be based on the rules of the file name to clean up a small portion at a time, such as only clean res/layout in the beginning of item_of files.
    2. Lint analysis seems to be not completely accurate, or not enough intelligence, such as a drawable is only a layout reference, and this layout is unused, lint may not find this drawable is unused, This requires that we repeat the previous steps several times until count is 0.
    3. Lint can only analyze the resource file, which is the Res directory file, if you want to parse the Java file also need other methods, and, it is possible that a resource file is referenced by a Java file, and this Java file is unused, so this resource file will escape lint check, So we'd better clean up the Java file and clean up the resource file.
Clean up Java files

First, or to find unused files, or use tools, I use the ucdetector, that is, unused Code Detector, the use of the method is not said, direct Google a bit.

Installing Eclipse's ucdetector plugin, performing a check on the project, could take a long time, and I checked for two hours. As with lint, the result is output to a text file, which is also a row for each problem, so as long as the line analysis is done, for example:

?

1 2 com.**. Sampleadapter.<init> (Sampleadapter.java: 18   class "Sampleadapter" has 0 references        Sampleadapter org.ucdetector.analyzeMarkerReference com.**. Sampleadapter.<init> (Sampleadapter.java: 56 )   change visibility of Member class "Sampleadapter.viewholder" to private -may cause compile errors!   sampleadapter.viewholder       Org.ucdetector.analyzeMarkerVisibilityPrivate

You can see that the results contain a lot of information, such as a class is not used, the visibility of a method is too large, the same, now only to deal with the useless class file, the other no matter.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 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);         }     } }

Through the above code basically can find useless to the class, or suggest not directly delete but the result output, because after the result you will find a lot of files you do not want to delete, such as:

?

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

Some of the files in the class library may also be detected, for this kind of directly in the if condition filter out, it may also be some of their own files temporarily useless but do not want to delete, filtered from the results.

Summarize

Cleaning up Resources is two steps:

    1. Find unused resources
    2. Clean up these resources on demand

Through ucdetector and Lint can basically detect the Unusedresource related issues in your project. Generally like the method of visibility, a method is useless to this problem, do not deal with, change to the corresponding file manual processing, the main processing is that some files or classes are not used, there is a test report, analysis of the report on the line. This kind of report usually reports a problem per line and each line of text is regular (the tool generates a certain regularity), filtering out the information we need on a regular basis.

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.