Android performance Optimization: Use Lint to optimize code, remove excess resources

Source: Internet
Author: User

After reading this article you will learn:

      • Objective
      • What is Lint
      • Brief introduction of Lint working mode
      • Run Lint from the command line
      • Using Lint in Android Studio
      • Build code specifications in the team to improve the level of reduced issues
      • Lint can not offs, though.
        • Ignore Lint warnings in Java code
        • Ignore Lint warnings in XML code
      • Configuring Lint in Gradle
      • Automatically delete the found useless resource file
      • Summarize
      • Thanks

Objective

In order to ensure that the code does not have functional problems, the completion of business development, the pursuit of programmers have to pursue the code of the specification, maintainability.

Today, the goal of "becoming a good programmer" will be to work with you to refine our code with Lint.

What is Lint

Lint is a code scanning analysis tool provided by Android Studio that can help us discover code structure/quality issues while providing some solutions, and this process does not require our handwriting test cases.

Each problem that Lint discovers has descriptive information and rank (similar to a bug found in testing), and we can easily locate the problem and resolve it at the same time as the severity.

Of course, this "severity" We can manually adjust, some of the principles of the problem cannot be violated, must be raised to error, and some individual problems can be ignored, after all, err who can have no.

Brief introduction of Lint working mode

Lint will check the source files of our Android project based on pre-configured detection criteria, identify potential bugs or areas that can be optimized, and optimize the content to include the following:

    • Correctness: not perfect coding, such as hard coding, using outdated APIs, etc.
    • Performance: Code that affects performance, such as static references, circular references, etc.
    • Internationalization: Internationalization, direct use of Chinese characters, no use of resource references, etc.
    • Security: Unsafe coding, such as allowing the use of javascriptinterface in WebView
    • ...

Lint the process of detecting the code is as follows:

    • App source files : including Java code, XML code, icons, and proguard configuration files, etc.
    • lint.xml: The execution standard configuration file for lint detection, we can modify it to allow or prohibit reporting some problems
Run Lint from the command line

Lint's command is simple:

<project directory>

Lint can also be run with Gradle:

Windows:

gradlew lint

Mac:

./gradlew lint

Specific command-line related actions are not introduced here, because this process is too painful, the previous command line run Lint after the XML file to let you experience:

The students who look uncomfortable and want to know how to use Lint from the command line can click here to go to the official study.

Let's go straight into Lint's GUI operation.

Using Lint in Android Studio

The Lint is built into Android Studio, and we can use it directly with little hands.

Lint using the path:
toolbar, Analyze, Inspect Code ...

Clicking Inspect Code will pop up the check box dialog:

The default is to check the entire project, we can click Custom scope to customize the scope of the check.

Click the drop-down box on the right and the following options appear:

Each of them is:

    • Project files: all project documents
    • Project Production Files: code file for projects
    • Project Test Files: Testing file for projects
    • OpenFiles: currently open file
    • Module ' app ': the main app module
    • Current file:
    • ...

In addition to the built-in options we can also select a specific class to check, click on the Red box in the section:

will play the Custom Range selection box, default is empty, we can click on the upper left corner of the "+" sign to add a check range:


- Local: Available only for current projects
- Shared: Other Android Studio projects can also be used

We chose Shared, and then a handsome name "Shixincutelint", by default by the project display, at this time the number of files checked is 0:

The four buttons on the right side indicate the type to be manipulated:

    • include: Includes files within the current folder, but does not include his subfolders
    • Include recursively: Includes all folders in the current folder and its subfolders, recursively add
    • Exclude: Remove the current folder, excluding subfolders
    • Exclude recursively: Remove the current folder and all subfolders

After we click on the app folder on the left, click the Include recursively button on the right to add all the files under the app to the checklist:

As you can see, the files under the app are all green, with a total of 689 folders to scan.

Click OK to detect, wait a moment, will pop up the inspection dialog box, display the results of the inspection, did not expect my code actually have 1769 warning! The numbers are shocking:

We mainly focus on the warning inside the red box, first look at my code performance what is the problem:

Haha, did not expect me to have so much progress space!

Can see, Lint is really artifact, can help us to find that we ignore or not aware of the problem, especially performance aspects, if you think your code want to optimize and do not know where to start, may let Lint give you finger road.

Building code specifications in teams: raising and lowering the level of problems

While Lint can help us check the code, when working with multiple people, we expect to find problems and solve problems when writing code.

Given the uneven level of team members and the fact that it is sometimes difficult to ensure quality by personal awareness, you can modify Lint's warning level for specific issues and alert members with the most intuitive IDE hints.

The severity of Lint warnings is as follows:

    • Unused Entry: No use of attributes, gray, very inconspicuous
    • Typo: spelling mistakes, green wavy underlines, not too noticeable
    • Server problem: Servers error? It seems not.
    • Info: Note document, green, more conspicuous
    • Weak Warning: Weaker warning, less hint
    • Warning: Warning, slightly conspicuous
    • Error: The most conspicuous one

In daily development, a better programmer will focus on Warning's warnings, optimizing the code based on warnings, but that's only a small part. But the red Error is not the same, basically see just want to eliminate.

Let's take a name spelling error for example.

The class, object, and traverse spelling errors don't seem to be a problem, but if you've seen a lot of meaningless or wrong names, you're going to agree with what I'm doing next.

The default spelling error is TYPO, the hint is weak, so it is often ignored:

The above String type variable login is written as logn,lint default for spelling errors is a downward wavy line, very inconspicuous. Let's change it.

Open preferences/settings, search for inspections, the Lint detection configuration page appears:

To change the spelling warning level, search for "spelling":

Then select the Typo that appear, then click on the right Severity is the severity, change to Error,ok.

As you can see, now the spelling error will appear red error warning, so you are not good to write variable name!

Lint, though good, can not offs.

Lint is like a neat and tidy patient, although can let our code clean a lot, but if really want to put it hint of the whole solution, I am afraid the boss to be angry: give you pay every day to play computer, how not caller it?!

Some warnings from the Lint are indeed unnecessary, and we can choose to ignore them. Ignoring warnings can be divided into two types:

    1. In the Java code
    2. In the XML folder
Ignore Lint warnings in Java code

Annotations that ignore Lint warnings are similar to @SuppressWarnings, @SuppressLint ("ignored warning names").

The following code demonstrates how to ignore Lint warnings for using the new API:

@SuppressLint("NewApi")@OverridepublicvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);}

If you don't know the name of the warning you want to ignore, simply ignore all and, of course, the current class/Method/object:

@SuppressLint("all")
Ignore Lint warnings in XML code

Only two steps:

    1. Declaring the tools namespace in XML
    2. Use tools:ignore= "ignored warning name"

For example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              xmlns:tools="http://schemas.android.com/tools"              tools:ignore="all"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:orientation="vertical"              android:background="@color/white">
Configuring Lint in Gradle

Gradle can also configure key operations for Lint, such as whether to turn on Lint warnings or to turn off specified warnings.

Add lintoptions{...} to the Build.gradle under module, the sample code is as follows:

android {  ...  lintOptions {    // Turns off checks for the issue IDs you specify.    disable ‘TypographyFractions‘,‘TypographyQuotes‘    // Turns on checks for the issue IDs you specify. These checks are in    // addition to the default lint checks.    enable ‘RtlHardcoded‘,‘RtlCompat‘, ‘RtlEnabled‘    // To enable checks for only a subset of issue IDs and ignore all others,    // list the issue IDs with the ‘check‘ property instead. This property overrides    // any issue IDs you enable or disable using the properties above.    check ‘NewApi‘, ‘InlinedApi‘    // If set to true, turns off analysis progress reporting by lint.    quiet true    // if set to true (default), stops the build if errors are found.    abortOnError false    // if true, only report errors.    ignoreWarnings true  }}...
Automatically delete the found useless resource file

Code iteration version of a lot, it is easy to leave some useless code, resource files, we can use Lint to clear.

Click the Android Studio toolbar, Analyze, Run inspection by Name:, enter what you want to detect, this is a useless resource.

Then select the Unused resources, then select the range and start testing.

There are so many useless files detected:

Note that there is a workaround on the right:Remove all Unused Resources, put a big picture to be conspicuous:

After clicking, boom, the world is quiet.

Summarize

Lint is a good programmer friends, my day provinces, today Lint?!

Welcome to scan Follow my public number Android Evolution , the first time to read the article ~

Thanks

Https://developer.android.com/studio/write/lint.html
http://blog.csdn.net/u010687392/article/details/47835743
Http://www.jianshu.com/p/991155725a68

Android performance Optimization: Use Lint to optimize code, remove excess resources

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.