Android app slimming (removal of unused resources in engineering) detailed _android

Source: Internet
Author: User
Tags readline visibility

Remove unused resources from the Android project

The project needs to change again, the UI a tune again, the result is a project in a heap has not used but did not clean up the garbage resources, not to mention the size of the project, for the new entrants to the project or to see the code of other modules, these resources may also be not clean up the resource can 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.

Cleaning Up resource files

To clean up the unused resources, the first job of course is to find them, and we know that there is a tool in the Anroid SDK called Lint that can help us look at the problems in the project, one of which is to look for resources that are not available, so this is a simple step to executing the following commands for the project that needs to be cleaned up:

Lint--check "Unusedresources" [Project_path] > Result.txt

After the execution of the above command in the project on the unusedresources problems are saved to the Result.txt, first look at Result.txt content

Res/values/arrays.xml:202:warning:the resource R.array.msg_my_friend_category_items appears to be unused [ Unusedresources]
^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 worthless. With this information, the next need to do is to analyze the information, manual analysis is not realistic, because this file may be very large, such as I executed the above command file has 2212 lines, this kind of thing, of course, to the computer to solve.

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

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

So still can be very convenient to get which file or even which line has a problem, I deal with only clean up the useless files, like the top of the res/values/arrays.xml:202 there is no tube, below see how to clean up the unused resources file.

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, a few lines of code, that is, read every line of the Result.txt file, according to the conditions you need to filter out the lines do not need to be processed (for example, I just want to clean anim, drawable and layout, so filter out the Res/value directory of information, and ignore AppCompat related information), each line ":" Before the string is the file name, found the file name to deal with, directly delete, or print out, or write to a file to reconfirm the confirmation to delete, When the results are written to a file, we can see if the file has a file that is not available but still does not want to be deleted. If there is, the processing method is also very simple, remove this line or simply make a mark, such as playing in front of #, and then read the file to the unmarked lines of the corresponding file deleted.

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

1. Some layout files that you may have used before, and used in the corresponding Java file in the layout layout of the ID, such as the control of some IDs set Onclicklistener, and in the onclick switch ... Case reference to these IDs, but in the end without this layout, then this layout is Unusedresource, but the previous reference to its Java code in the layout of some of the ID of the reference is not clear, this time delete this layout will be an error , you can choose to clean up the Java code for the error, as they actually dead code. Or to clean up a portion of the resource files, such as cleaning the layout first, and then cleaning the drawable, for each item can also be based on the rules of the file name each time to clean up a small number of, such as only the res/layout to clean up the item_of file ...

2.lint analysis seems to be not completely accurate, or not intelligent, 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 repeatedly until count is 0.

3.lint can only analyze resource files, that is, files in the Res directory, if you want to analyze Java files 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 the lint check, So we'd better clean up the Java files and clean the resource files first.

Cleaning up Java files

First or to find unused files, or use tools, I use is ucdetector, that is, unused Code detector, the use of the method is not said, Google directly.

Installing Eclipse's Ucdetector plug-in, which may take a long time to perform a project check, I checked for two hours. As with lint, the results are exported to a text file, which is also a row for each problem, so just parse the line, like this:

Com.. Sampleadapter. (sampleadapter.java:18) Class "Sampleadapter" has 0 references sampleadapter org.ucdetector.analyzeMarkerReference
com. Sampleadapter. (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 test results contain a lot of information, such as a class is not used, a method of visibility is too large, and so on, the same, now only to deal with the unused class files, and other regardless.

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") & amp;&!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 can basically find useless class, or recommend not directly delete the result output, because the result of the loss after you will find a lot of files you do not want to delete, such as:

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

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

Summarize

Cleaning up Resources is two steps:

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

Through Ucdetector and lint basically can detect the project Unusedresource related problems, generally like method visibility, a method is not used to this problem, do not deal with it, change to the corresponding file when the manual treatment to forget, The main treatment is that some files or classes are not used, there are test reports, analysis of the report on the line. This kind of report is usually a question for each row and the text is regular (the tool generated is certainly regular), filter out the information we need by law.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.