Skip to content

Most visited

Recently visited

navigation

Improve Your Code with Lint

In addition to testing your Android application to ensure that it meets its functional requirements, it's important to ensure that your code has no structural problems. Poorly structured code can impact the reliability and efficiency of your Android apps and make your code harder to maintain. For example, if your XML resource files 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.

Overview

Android Studio provides a code scanning tool called lint that can help you to identify and correct problems with the structural quality of your code without your having to execute the app or write 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. Also, you can lower the severity level of a problem to ignore issues that are not relevant to your project, or raise the severity level to highlight specific problems.

The lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization. When using Android Studio, configured lint and IDE inspections run whenever you build your app. However, you can manually run inspections or run lint from the command line.

Note: When your code is compiled in Android Studio, additional IntelliJ code inspections run to streamline code review.

Figure 1 shows how the lint tool processes the application source files.

Figure 1. Code scanning workflow with the lint tool

Application source files
The source files consist of files that make up your Android project, including Java and XML files, icons, and ProGuard configuration files.
The lint.xml file
A configuration file 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 either from the command line or in Android Studio (see Manually Run Inspections). 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 either in the console or in the Inspection Results window in Android Studio. See Manually Run Inspections.

Run lint from the command line

To run lint against a list of files in a project directory, use the following command:

lint [flags] <project directory>

For example, you can issue the following command to scan the files 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 prefix.

lint --check MissingPrefix myproject 

To see the full list of flags and command-line arguments supported by the tool, use the following command:

lint --help

Example lint output

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

$ lint Earthquake

Scanning Earthquake: ...............................................................................................................................
Scanning Earthquake (Phase 2): .......
AndroidManifest.xml:23: Warning: <uses-sdk> tag appears after <application> tag [ManifestOrder]
  <uses-sdk android:minSdkVersion="7" />
  ^
AndroidManifest.xml:23: Warning: <uses-sdk> tag should specify a target API level (the highest verified version; when running on later versions, compatibility behaviors may be enabled) with android:targetSdkVersion="?" [UsesMinSdkAttributes]
  <uses-sdk android:minSdkVersion="7" />
  ^
res/layout/preferences.xml: Warning: The resource R.layout.preferences appears to be unused [UnusedResources]
res: Warning: Missing density variation folders in res: drawable-xhdpi [IconMissingDensityFolder]
0 errors, 4 warnings

The output above lists four warnings and no errors: three warnings (ManifestOrder, UsesMinSdkAttributes, and UnusedResources) in the project's AndroidManifest.xml file, and one warning (IconMissingDensityFolder) in the Preferences.xml layout file.

Run lint with Gradle

If your project includes build variants, you can use the Gradle wrapper to invoke the lint task for all your variants by entering one of the following commands from the root directory of your project:

If you instead want to run the lint task for only a specific build variant, you must capitalize the variant name and prefix it with lint.

gradlew lintDebug

When the lint tool completes its checks, the lint report provides two paths to the XML and HTML versions of the lint report. To learn more about running Gradle tasks from the command line, read Build Your App from the Command Line.

Configure lint

By default when you run a lint scan, the tool checks for all issues that lint supports. 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 specific issues that are not relevant to your project and, you can configure lint to report non-critical issues at a lower severity level.

You can configure lint checking for different levels:

Configure 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:

Configure the lint file

You can specify your lint checking preferences in the lint.xml file. If you are creating this file manually, place it in the root directory of your Android project.

The lint.xml file consists of an enclosing <lint> parent tag that contains one or more children <issue> elements. Lint defines a unique id attribute value for each <issue>.

<?xml version="1.0" encoding="UTF-8"?>
    <lint>
        <!-- list of issues to configure -->
</lint>

You can change an issue's severity level or disable lint checking for the issue by setting the severity attribute in the <issue> tag.

Tip: For a full list of lint-supported issues and their corresponding issue IDs, run the lint --list command.

Sample lint.xml file

The following example shows the contents of a lint.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- Disable the given check in this project -->
    <issue id="IconMissingDensityFolder" severity="ignore" />

    <!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
    <issue id="ObsoleteLayoutParam">
        <ignore path="res/layout/activation.xml" />
        <ignore path="res/layout-xlarge/activation.xml" />
    </issue>

    <!-- Ignore the UselessLeaf issue in the specified file -->
    <issue id="UselessLeaf">
        <ignore path="res/layout/main.xml" />
    </issue>

    <!-- Change the severity of hardcoded strings to "error" -->
    <issue id="HardcodedText" severity="error" />
</lint>

Configure lint checking for Java and XML source files

You can disable lint from checking your Java and XML source files.

Tip: You can manage the lint checking feature for your Java or XML source files in the Default Preferences dialog. Select File > Other Settings > Default Settings, and then in the left pane of the Default Preferences dialog, select Editor > Inspections.

Configuring lint checking in Java

To disable lint checking specifically 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
public void onCreate(Bundle savedInstanceState) {
    super.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")
public class FeedProvider extends ContentProvider {

To suppress checking for all lint issues in the Java file, use the all keyword, like this:

@SuppressLint("all")

Configuring lint checking in XML

You can use the tools:ignore attribute to disable lint checking for specific sections of your XML files. Put the following namespace value in the lint.xml file so the lint tool recognizes the attribute:

namespace xmlns:tools="http://schemas.android.com/tools"

The following example shows how you can turn off lint checking for the UnusedResources issue in the <LinearLayout> element of an XML layout file. 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.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="UnusedResources" >

    <TextView
        android:text="@string/auto_update_prompt" />
</LinearLayout>

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"

Configure lint options with Gradle

The Android plugin for Gradle allows you to configure certain lint options, such as which checks to run or ignore, using the lintOptions {} block in your module-level build.gradle file. The following code snippet shows you some of the properties you can configure:

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
  }
}
...

Manually run inspections

You can manually run configured lint and other IDE inspections by selecting Inspect Code > Analyze. The results of the inspection appear in the Inspection Results window.

Set the inspection scope and profile

Select the files you want to analyze (inspection scope) and the inspections you want to run (inspection profile), as follows:

  1. In the Android view, open your project and select the project, a folder, or a file that you want to analyze.
  2. From the menu bar, select Analyze > Inspect Code.
  3. In the Specify Inspection Scope dialog, review the settings. Specify Inspection Scope

    Figure 2. Review the inspection scope settings

    The combination of options that appear in the Specify Inspection Scope dialog varies depending on whether you selected a project, folder, or file. You can change what to inspect by selecting one of the other radio buttons. See Specify Inspection Scope dialog for a description of all of the possible fields on the Specify Inspection Scope dialog.

    • When you select one project, file, or directory, the Specify Inspection Scope dialog displays the path to the Project, File, or Directory you selected.
    • When you select more than one project, file, or directory, the Specify Inspection Scope dialog displays a checked radio button for Selected files.
  4. Under Inspection profile, keep the default profile (Project Default).
  5. Click OK to run the inspection. Figure 3 shows lint and other IDE inspection results from the Inspect Code run:

    Figure 3. Select an issue to see its resolution

  6. In the left pane tree view, view the inspection results by expanding and selecting error categories, types, and issues.

    The right pane displays the inspection report for the selected error category, type, or issue and provides the name and location of the error. Where applicable, the inspection report displays other information such as a problem synopsis to help you correct the problem.

  7. In the left pane tree view, right-click a category, type, or issue to display the context menu.

    Depending on the context, you can do all or some of the following: jump to source, exclude and include selected items, suppress problems, edit settings, manage inspection alerts, and rerun an inspection.

For descriptions of the left-side Toolbar buttons, context menu items, and inspection report fields, see Inspection Tool Window.

Use a custom scope

You can use one of the custom scopes provided in Android Studio, as follows:

  1. In the Specify Inspection Scope dialog, click Custom scope.
  2. Click the Custom scope drop-down list to display your options.

    Choose Inspection Scope

    Figure 4. Select the custom scope you want to use

    • Project Files: All of the files in the current project.
    • Project Production Files: Only the production files in the current project.
    • Project Test Files: Only the test files in the current project. See Test Types and Location.
    • Open Files: Only the files you have open in the current project.
    • Module <your-module>: Only the files in the corresponding module folder in your current project.
    • Current File: Only the current file in your current project. Appears when you have a file or folder selected.
    • Class Hierarchy: When you select this one and click OK, a dialog appears with all of the classes in the current project. Use the Search by Name field in the dialog to filter and select the classes to inspect. If you do not filter the classes list, code inspection inspects all of the classes.
  3. Click OK.

Create a custom scope

When you want to inspect a selection of files and directories that is not covered by any of the currently available custom scopes, you can create a custom scope.

  1. In the Specify Inspection Scope dialog, select Custom scope.
  2. Click the three dots after the Custom Scope drop-down list.

    Figure 5. Specify Inspection Scope dialog

    The Scopes dialog appears.

    Figure 6. Create a custom scope

  3. Click Add to define a new scope.
  4. In the resulting Add Scope drop-down list, select Local.

    Both the local and shared scopes are used within the project for the Inspect Code feature. A Shared scope can also be used with other project features that have a scope field. For example, when you click Edit Settings to change the settings for Find Usages, the resulting dialog has a Scope field where you can select a shared scope.

    Figure 7. Select a shared scope from the Find Usages dialog

  5. Give the scope a name and click OK.

    The right pane of the Scopes dialog populates with options that enable you to define the custom scope.

  6. From the drop-down list, select Project.

    A list of available projects appears.

    Note: You can create the custom scope for projects or packages. The steps are the same either way.

  7. Expand the project folders, select what you want to add to the custom scope, and click one of the buttons on the right.

    Figure 8. Define a custom scope

    • Include: Include this folder and its files, but do not include any of its subfolders.
    • Include Recursively: Include this folder and all of its files and subfolders and their files.
    • Exclude: Exclude this folder and its files, but do not exclude any of its subfolders.
    • Exclude Recursively: Exclude ths folder and all of its files and subfolders and their files.

    Figure 9 shows that the main folder is included, and that the java folder is included recursively. The blue indicates partially included folders and the green indicates recursively included folders and files.

    Figure 9. Example pattern for a custom scope

    • If you select the java folder and click Exclude Recursively, the green highlighting goes away on the java folder and all folders and files under it.
    • If you instead select the green highlighted MainActivity.java file and click Exclude, MainActivity.java is no longer green highlighted but everything else under the java folder is green highlighted.
  8. Click OK. The custom scope appears at the bottom of the drop-down list.

Review and edit inspection profiles

Android Studio comes with a selection of lint and other inspection profiles that are updated through Android updates. You can use these profiles as is or edit their names, descriptions, severities, and scopes. You can also activate and deactivate entire groups of profiles or individual profiles within a group.

To access the Inspections dialog:

  1. Select Analyze > Inspect Code.
  2. In the Specify Scope dialog under Inspection Profile, click More.

    The Inspections dialog appears with a list of the supported inspections and their descriptions.

    Figure 10. Supported inspections and their descriptions

  3. Select the Profile drop-down list to toggle between Default (Android Studio) and Project Default (the active project) inspections. For more information, see this IntelliJ Specify Inspection Scope Dialog page.
  4. In the Inspections dialog in the left pane, select a top-level profile category, or expand a group and select a specific profile. When you select a profile category, you can edit all of the inspections in that category as a single inspection.
  5. Select the Manage drop-down list to copy, rename, add descriptions to, export, and import inspections.
  6. When you're done, click OK.
This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a one-minute survey?
Help us improve Android tools and documentation.