Lint로 코드 개선하기 Improve Your Code with Lint
안드로이드 애플리케이션이 기능 요구사항을 충족시키는지에 대한 테스팅에 추가하여, 코드가 구조적으로 문제가 없도록 하는 것이 중요합니다.
잘못 구조화된 코드는 안드로이드 app의 안정성과 효율성에 영향을 미쳐 및 코드 유지 관리를 어렵게 만들 수 있습니다.
예를 들어, XML 리소스 파일에 사용되지 않는 네임스페이스가 포함된 경우, 이 네임스페이스는 공간을 차지하여 불필요한 처리를 초래합니다.
더 이상 지원되지 않는 엘리먼트나 타겟 API 버전이 지원하는 않는 API calls와 같은 다른 구조적 문제는 코드가 제대로 실행되지 못하게 할 수 있습니다.
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 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
안드로이드 스튜디오는 app을 실행하거나 테스트 케이스를 작성하지 않고도, 코드의 구조적 품질 문제를 쉽게 파악해서 교정하는 것을 도와주는 Lint라는 코드 스캐닝 도구를 제공합니다.
도구가 탐지한 각각의 문제는, 설명 메시지와 심각도 수준을 보고하기 때문에, 조치해야 할 심각한
개선사항의 우선 순위를 정할 수 있습니다.
또한 프로젝트와 관련이 없는 문제를 무시하거나, 또는 심각도 수준을 높이도록 문제의 심각도 수준을 구성할 수 있습니다.
이 Lint 도구는 명령-줄 인터페이스를 갖고 있어서 이 도구를 자동화된 테스트 프로세스에 쉽게 통합시킬 수 있습니다.
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 configure 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.
Lint 도구는 정확성, 보안, 성능, 사용성, 접근성, 국제화 측면에서 잠재적 버그 및 최적화 개선을 위하여 안드로이드 프로젝트 소스 파일을 체크합니다.
명령-줄 또는 안드로이드 스튜디오에서 Lint를 실행시킬 수 있습니다.
The Lint tool checks your Android project source files 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 run when your code is compiled in Android Studio 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 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 identified by the location in the source files 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 configured Lint and IDE inspections run automatically whenever you build your app. The IDE inspections are configured along with the Lint checks to run IntelliJ code inspections to streamline code review.
Note: To view and modify inspection severity levels, use the File > Settings > Editor > Inspections menu to open the Inspection Configuration page with a list of the supported inspections.
With Android Studio, you can also run Lint inspections for a specific build variant, or for all build variants from the build.gradle
file. Add thelintOptions
property to the android
settings in the build file. This code snippet from a Gradle build file 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 true
// if true, stop the gradle build if errors are found
abortOnError false
// if true, only report errors
ignoreWarnings true
}
...
}
To manually run inspections in Android Studio, from the application or right-click menu, choose Analyze > Inspect Code. The Specify Inspections Scopedialog appears so you can specify the desired inspection scope and profile.
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 files in a project directory:
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:
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 in this project. Three warnings (ManifestOrder
, UsesMinSdkAttributes
, and UnusedResources
) were found in the project's AndroidManifest.xml
file. The remaining warning (IconMissingDensityFolder
) was found in the Preferences.xml
layout file.
Configuring 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 specific issues that are not relevant to your project and configure Lint to report non-critical issues at a lower severity level.
You can configure Lint checking at different levels:
- Globally, for the entire project
- Per project module
- Per production module
- Per test module
- Per open files
- Per class hierarchy
- Per Version Control System (VCS) scopes
Configuring 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 finds 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:
- In Android Studio, open your project.
- Select File > Other Settings > Default Settings.
- In the Default Preferences dialog, select Editor > Inspections.
- In the Profile field, select Default or Project Default to set the scope for Android Studio or just for this project, respectively.
- Expand a category and change the Lint settings as needed.
You can select individual checks, or entire categories.
- Click OK.
To produce a list of Lint checks displayed in the Inspection Results window:
- In Android Studio, open your project and select a portion of your project that you want to test.
- Select Analyze > Inspect Code.
- In the Specify Inspection Scope dialog, select the inspection scope and profile.
The scope specifies the files you want to analyze, and the profile specifies the Lint checks you’d like to perform.
- If you want to change the Lint settings, click …. In the Inspections dialog, optionally click Manage to define a new profile, specify the Lint settings you want, and then click OK.
In the Inspections dialog, you can search for a string to find Lint checks. Note that changing Lint settings for a profile in the Inspections dialog doesn’t change the default settings, as described in the previous procedure. It does change the settings for profiles displayed in the Inspectionsdialog, however.
- Click OK.
The results appear in the Inspection Results window, organized by category.
Configuring 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. If you are configuring Lint preferences in Android Studio, the lint.xml
file is automatically created and added to your Android project for you.
The lint.xml
file consists of an enclosing <lint>
parent tag that contains one or more children <issue>
elements. Each <issue>
is identified by a unique id
attribute value, which is defined by Lint.
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- list of issues to configure -->
</lint>
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 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>
Configuring lint checking in Java and XML source files
You can disable Lint checking from your Java and XML source files.
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 files.
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 theNewApi
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. In order for this attribute to be recognized by the Lint tool, the following namespace value must be included in your XML file:
namespace 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 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"
'User Guide' 카테고리의 다른 글
레이아웃 편집기로 UI 디자인 하기 Design a UI with Layout Editor (13) (0) | 2016.06.02 |
---|---|
Improve Code Inspection with Annotations (12) (0) | 2016.06.02 |
app 만들기 Write Your App (10) (0) | 2016.06.01 |
Add Code from a Template (9) (0) | 2016.06.01 |
안드로이드 라이브러리 만들기 Create an Android Library (8) (0) | 2016.06.01 |
댓글