Sunteți pe pagina 1din 9

Android Developers

Improve Your Code with Lint


In addition to testing that your Android
application meets its functional
requirements, it's important to ensure that
your code has no structural problems.
Poorly structured code can impact the
reliability and efciency of your Android
apps and make your code harder to
maintain. For example, if your XML
resource les contain unused
namespaces, this takes up space and
incurs unnecessary processing. Other
structural issues, such as use of
deprecated elements or API calls that are
not supported by the target API versions,
might lead to code failing to run correctly.

In This Document
Overview
Running lint from Android
Studio
Running lint from the
command-line
Conguring lint
Conguring Lint in Android
Studio
Conguring the lint le
Conguring lint checking in
Java and XML source les

See Also
Using Android Annotations

Overview
Android Studio provides a code scanning tool
called Lint that can help you to easily identify and correct problems with the
structural quality of your code, without having to execute the app or write any test
cases. Each problem detected by the tool is reported with a description message
and a severity level, so that you can quickly prioritize the critical improvements that
need to be made. You can also congure a problem's severity level to ignore issues
that are not relevant for your project, or raise the severity level. The tool has a
command-line interface, so you can easily integrate it into your automated testing
process.
The Lint tool checks your Android project source les for potential bugs and
optimization improvements for correctness, security, performance, usability,
accessibility, and internationalization. You can run Lint from the command-line or
from Android Studio.
Note: In Android Studio, additional IntelliJ code inspections

(https://www.jetbrains.com/help/idea/2016.1/code-inspection.html)

run when your code is

compiled in Android Studio to streamline code review.


Figure 1 shows how the Lint tool processes the application source les.

Figure 1. Code scanning workow with the Lint tool

Application source les


The source les consist of les that make up your Android project, including
Java and XML les, icons, and ProGuard conguration les.
The lint.xml le
A conguration le that you can use to specify any Lint checks that you want
to exclude and to customize problem severity levels.
The Lint tool
A static code scanning tool that you can run on your Android project from the
command-line or Android Studio. The Lint tool checks for structural code
problems that could affect the quality and performance of your Android
application. It is strongly recommended that you correct any errors that Lint
detects before publishing your application.
Results of Lint checking
You can view the results from Lint in the console or in the Event Log in
Android Studio. Each issue is identied by the location in the source les
where it occurred and a description of the issue.
The Lint tool is automatically installed as part of the Android SDK Tools revision 16

or higher.

Running lint in Android Studio


In Android Studio, the congured Lint and IDE inspections run automatically
whenever you build your app. The IDE inspections are congured along with the Lint
checks to run IntelliJ code inspections (https://www.jetbrains.com/help/idea/2016.1/codeinspection.html)

to streamline code review.

Note: To view and modify inspection severity levels, use the File > Settings >
Editor > Inspections menu to open the Inspection Conguration page with a list
of the supported inspections.
With Android Studio, you can also run Lint inspections for a specic build variant, or
for all build variants from the build.gradle le. Add the lintOptions property to
the android settings in the build le. This code snippet from a Gradle build le
shows how to set the quiet option to true and the abortOnError option to false.
android {
lintOptions {
// set to true to turn off analysis progress reporting by lint
quiet ttrruuee
// if true, stop the gradle build if errors are found
abortOnError ffaallssee
// if true, only report errors
ignoreWarnings ttrruuee
}
...
}

To manually run inspections in Android Studio, from the application or right-click


menu, choose Analyze > Inspect Code. The Specify Inspections Scope dialog
appears so you can specify the desired inspection scope and prole.
Results of each inspection appear in the Inspection tool window. You can see a
problem synopsis inline by hovering over an inspection error, or display the error's
full issue explanation by selecting it.

Running lint from the Command-Line


To run Lint against a list of les in a project directory:

lint [flags] <project directory>

For example, you can issue the following command to scan the les under the
myproject directory and its subdirectories. The issue ID MissingPrefix tells Lint

to only scan for XML attributes that are missing the Android namespace prex.
lint --check MMiissssiinnggPPrreeffiixx myproject

To see the full list of ags and command-line arguments supported by the tool:
lint --help

Example lint output


The following example shows the console output when the Lint command is run
against a project called Earthquake.
$ lint EEaarrtthhqquuaakkee

SSccaannnniinngg EEaarrtthhqquuaakkee: ....................................................


SSccaannnniinngg EEaarrtthhqquuaakkee (PPhhaassee 2): .......
AAnnddrrooiiddMMaanniiffeesstt.xml:23: WWaarrnniinngg: <uses-sdk> tag appears after <applicatio
<uses-sdk android:minSdkVersion="7" />
^
AAnnddrrooiiddMMaanniiffeesstt.xml:23: WWaarrnniinngg: <uses-sdk> tag should specify a target A
<uses-sdk android:minSdkVersion="7" />
^
res/layout/preferences.xml: WWaarrnniinngg: TThhee resource R.layout.preferences ap
res: WWaarrnniinngg: MMiissssiinngg density variation folders iinn res: drawable-xhdpi
0 errors, 4 warnings

The output above lists four warnings and no errors in this project. Three warnings
(ManifestOrder, UsesMinSdkAttributes, and UnusedResources) were found in
the project's AndroidManifest.xml le. The remaining warning
(IconMissingDensityFolder) was found in the Preferences.xml layout le.

Conguring lint
By default, when you run a Lint scan, the tool checks for all issues that are
supported by Lint. You can also restrict the issues for Lint to check and assign the
severity level for those issues. For example, you can disable Lint checking for

specic issues that are not relevant to your project and congure Lint to report
non-critical issues at a lower severity level.
You can congure Lint checking at different levels:
Globally, for the entire project
Per project module
Per production module
Per test module
Per open les
Per class hierarchy
Per Version Control System (VCS) scopes

Conguring Lint in Android Studio


The built-in Lint tool checks your code while you're using Android Studio. You can
view warnings and errors in two ways:
As pop-up text in the Code Editor. When Lint nds a problem, it highlights the
problematic code in yellow, or underlines the code in red for more serious
issues.
In the Lint Inspection Results window after you select Analyze > Inspect Code.
To set default Lint checks:
1. In Android Studio, open your project.
2. Select File > Other Settings > Default Settings.
3. In the Default Preferences dialog, select Editor > Inspections.
4. In the Prole eld, select Default or Project Default to set the scope
(https://www.jetbrains.com/help/idea/2016.1/specify-inspection-scope-dialog.html?origin=old_help)

Android Studio or just for this project, respectively.


5. Expand a category and change the Lint settings as needed.
You can select individual checks, or entire categories.
6. Click OK.
To produce a list of Lint checks displayed in the Inspection Results window:

for

1. In Android Studio, open your project and select a portion of your project that you
want to test.
2. Select Analyze > Inspect Code.
3. In the Specify Inspection Scope dialog, select the inspection scope
(https://www.jetbrains.com/help/idea/2016.1/specify-inspection-scope-dialog.html?origin=old_help)

and

prole.
The scope species the les you want to analyze, and the prole species the
Lint checks youd like to perform.
4. If you want to change the Lint settings, click . In the Inspections dialog,
optionally click Manage to dene a new prole, specify the Lint settings you
want, and then click OK.
In the Inspections dialog, you can search for a string to nd Lint checks. Note
that changing Lint settings for a prole in the Inspections dialog doesnt change
the default settings, as described in the previous procedure. It does change the
settings for proles displayed in the Inspections dialog, however.
5. Click OK.
The results appear in the Inspection Results window, organized by category.

Conguring the lint le


You can specify your Lint checking preferences in the lint.xml le. If you are
creating this le manually, place it in the root directory of your Android project. If
you are conguring Lint preferences in Android Studio, the lint.xml le is
automatically created and added to your Android project for you.
The lint.xml le consists of an enclosing <lint> parent tag that contains one or
more children <issue> elements. Each <issue> is identied by a unique id
attribute value, which is dened by Lint.
<?xml version="1.0" encoding="UTF-8"?>
<<lliinntt>>
<!-- list of issues to configure -->
<<//lliinntt>>

By setting the severity attribute value in the <issue> tag, you can disable Lint
checking for an issue or change the severity level for an issue.
Tip: To see the full list of issues supported by the Lint tool and their

corresponding issue IDs, run the lint --list command.

Sample lint.xml le
The following example shows the contents of a lint.xml le.
<?xml version="1.0" encoding="UTF-8"?>
<<lliinntt>>
<!-- Disable the given check in this project -->
<<iissssuuee id="IconMissingDensityFolder" severity="ignore" //>>
<!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
<<iissssuuee id="ObsoleteLayoutParam">>
<<iiggnnoorree path="res/layout/activation.xml" //>>
<<iiggnnoorree path="res/layout-xlarge/activation.xml" //>>
<<//iissssuuee>>
<!-- Ignore the UselessLeaf issue in the specified file -->
<<iissssuuee id="UselessLeaf">>
<<iiggnnoorree path="res/layout/main.xml" //>>
<<//iissssuuee>>

<!-- Change the severity of hardcoded strings to "error" -->


<<iissssuuee id="HardcodedText" severity="error" //>>
<<//lliinntt>>

Conguring lint checking in Java and XML source


les
You can disable Lint checking from your Java and XML source les.
Tip: If you are using Android Studio, you can use the File > Settings > Project
Settings > Inspections feature to manage the Lint checking to your Java or XML
source les.

Conguring lint checking in Java


To disable Lint checking specically for a Java class or method in your Android
project, add the @SuppressLint annotation to that Java code.
The following example shows how you can turn off Lint checking for the NewApi}
issue in the onCreate method. The Lint tool continues to check for the NewApi
issue in other methods of this class.
@SuppressLint("NewApi")
@Override
ppuubblliicc vvooiidd onCreate(BBuunnddllee savedInstanceState) {

ssuuppeerr.onCreate(savedInstanceState);
setContentView(R.layout.main);

The following example shows how to turn off Lint checking for the ParserError
issue in the FeedProvider class:
@SuppressLint("ParserError")
ppuubblliicc ccllaassss FFeeeeddPPrroovviiddeerr eexxtteennddss CCoonntteennttPPrroovviiddeerr {

To suppress checking for all Lint issues in the Java le, use the all keyword, like
this:
@SuppressLint("all")

Conguring lint checking in XML


You can use the tools:ignore attribute to disable Lint checking for specic
sections of your XML les. In order for this attribute to be recognized by the Lint
tool, the following namespace value must be included in your XML le:
nnaammeessppaaccee xmlns:tools="http://schemas.android.com/tools"

The following example shows how you can turn off Lint checking for the
UnusedResources issue for the <LinearLayout> element of an XML layout le.

The ignore attribute is inherited by the children elements of the parent element in
which the attribute is declared. In this example, the Lint check is also disabled for
the child <TextView> element.
<<LLiinneeaarrLLaayyoouutt
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="UnusedResources" >>
<<TTeexxttVViieeww
android:text="@string/auto_update_prompt" //>>
<<//LLiinneeaarrLLaayyoouutt>>

To disable more than one issue, list the issues to disable in a comma-separated
string. For example:
tools:ignore="NewApi,StringFormatInvalid"

To suppress checking for all Lint issues in the XML element, use the all keyword,

like this:
tools:ignore="all"

S-ar putea să vă placă și