1. 程式人生 > >Android靜態程式碼檢查工具Lint

Android靜態程式碼檢查工具Lint

轉自 https://blog.csdn.net/u012317510/article/details/78221218

 

前言

Android提供了一個叫做Lint的靜態程式碼檢查工具。Lint工具可以幫助你檢查可能影響應用質量和效能的程式碼問題。該工具會報告檢測到的每個問題並提供問題的描述資訊和嚴重級別,以便你可以快速地確定需要優先進行哪些改進。在使用Android Studio時,配置的Lint工具和IDE檢查會在你編寫程式碼時自動執行。當然,你也可以手動執行Lint工具。

Lint簡介

Lint支援6大類別的問題檢查,併為每個問題定義了唯一的id。要檢視Lint支援的問題以及對應的問題id的完整列表,可以執行 lint –list

 命令。

使用Android SDK tools目錄下的Lint,執行lint –list命令,如下所示:

D:\Android\sdk\tools>lint --list
Valid issue categories:
    Correctness
    Correctness:Messages
    Security
    Performance
    Usability:Typography
    Usability:Icons
    Usability
    Accessibility
    Internationalization
    Internationalization:Bidirectional Text

Valid issue id's:
"ContentDescription": Image without contentDescription
"AddJavascriptInterface": addJavascriptInterface Called
"ShortAlarm": Short or Frequent Alarm
"AllowAllHostnameVerifier": Insecure HostnameVerifier
"AlwaysShowAction": Usage of showAsAction=always
...
"NotSibling": RelativeLayout Invalid Constraints
"UnknownId": Reference to an unknown id
"UnknownIdInLayout": Reference to an id that is not in the current layout
"SuspiciousImport": 'import android.R' statement
"WrongFolder": Resource file in the wrong res folder

可以看到,Lint支援正確性、安全性、效能、易用性、可達性和國際化這6大類別的問題檢查,併為每個問題定義了唯一的id。

配置Lint

預設情況下,Lint會檢查所有支援的問題,並且所有的問題都有預設的嚴重級別。你可以限定Lint要檢查的問題,也可以指定問題的嚴重級別。例如,你可以禁止Lint檢查與專案無關的特定問題,也可以降低非關鍵問題的嚴重級別。

禁止Lint要檢查的問題有多種方式:

  • 在Java程式碼中使用@SuppressLint註解。
  • 在XML檔案中使用tools:ignore屬性。
  • 在build.gradle檔案中使用lintOptions塊。
  • 使用lint.xml檔案配置Lint。
  • 使用Android Studio配置Lint。

在Java程式碼中配置Lint

要禁止Lint檢查某個Java類或者方法的某個問題,你可以使用 @SuppressLint 註解。格式如下所示:

// 單個問題
@SuppressLint("id")

// 所有問題
@SuppressLint("all")

示例1:

@SuppressLint("NewApi")
public class MainActivity extends AppCompatActivity {
    ...
}

示例1示範瞭如何禁止Lint檢查MainActivity類中的NewApi問題。

示例2:

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
}

示例2示範瞭如何禁止Lint檢查onCreate()方法中的NewApi問題。

在XML檔案中配置Lint

要禁止Lint檢查XML檔案特定部分的某個問題,你可以使用 tools:ignore 屬性。格式如下所示:

<!-- 單個問題 -->
tools:ignore="id"

<!-- 多個問題 -->
tools:ignore="id1,id2"

<!-- 所有問題 -->
tools:ignore="all"

注意: 你需要在XML檔案中新增tools名稱空間,以使用tools:ignore屬性。如下所示:

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

示例1:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView2" />
</LinearLayout>

示例1示範瞭如何禁止Lint檢查LinearLayout元素及其子元素的HardcodedText問題。如果某個父元素聲明瞭tools:ignore屬性,那麼它的子元素會繼承此屬性。

示例2:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView1"
    tools:ignore="HardcodedText" />

示例2示範瞭如何禁止Lint檢查TextView元素的HardcodedText問題。

在build.gradle檔案中配置Lint

你可以在Android專案的模組的build.gradle檔案中使用 lintOptions 塊來配置Lint。例如,禁止或者增加某些問題的檢查。

下面這個示例示範了你可以配置的部分屬性:

android {
    ...
    lintOptions {
        // Turns off checks for the issue IDs you specify.
        disable 'HardcodedText', 'NewApi'
        // Turns on checks for the issue IDs you specify. These checks are in
        // addition to the default lint checks.
        enable 'RtlHardcoded', 'RtlCompat', 'RtlEnabled'
        // 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
    }
}

使用lint.xml檔案配置Lint

你可以在Android專案的模組的根目錄下使用 lint.xml 檔案來配置Lint。

lint.xml檔案由封閉的lint父標籤組成,該標籤包含一個或者多個issue子標籤。每個issue標籤表示一個問題。你可以在issue標籤中設定禁止Lint檢查此問題或者問題的嚴重級別。問題可以設定的嚴重級別有4種:informational、warning、error和fatal。

lint.xml檔案示例如下所示:

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

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

    <!-- Change the severity of given check to "error" -->
    <issue id="NewApi" severity="error" />
</lint>

使用Android Studio配置Lint

在Android Studio中,點選 Analyze > Inspect Code…,在彈出的對話方塊中你可以配置此次Lint檢查的範圍。如下圖所示:

配置Lint檢查的範圍.png

可以看到,我們可以指定此次Lint檢查的範圍為整個專案或者某個模組或者自定義的範圍。

點選此對話方塊中Inspection profile下方的  按鈕,在彈出的對話方塊中你可以配置Lint檢查的規則。如下圖所示:

配置Lint檢查的規則.png

可以看到,我們可以配置Lint開啟或者關閉某些問題的檢查以及問題的嚴重級別。

注意: 使用Android Studio配置Lint檢查的規則只對Android Studio自動執行的Lint檢查和通過該方式手動執行的Lint檢查起作用。

執行Lint

在使用Android Studio時,配置的Lint工具和IDE檢查會在你編寫程式碼時自動執行。Lint發現問題後,會用黃色高亮顯示有問題的程式碼,而對於更嚴重的問題,則會在程式碼下面顯示紅色的下劃線。

當然,你也可以手動執行Lint。手動執行Lint的方法主要有以下三種:

  • 使用Gradle執行Lint。
  • 使用Android Studio執行Lint。
  • 使用Android SDK中的獨立工具執行Lint(不常用)。

使用Gradle執行Lint

預設情況下,基於Gradle構建的Android專案已經包含了lint任務以及各種構建變種的lint任務。你可以在專案的根目錄下執行 gradlew tasks 命令檢視。如下所示:

E:\Android\LintDemo>gradlew tasks
...
Verification tasks
------------------
...
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
...

因此,你可以在專案的根目錄下執行 gradlew lint 命令來執行Lint。如下所示:

E:\Android\LintDemo>gradlew lint
...
:app:lint                 
Ran lint on variant release: 3 issues found
Ran lint on variant debug: 3 issues found
Wrote HTML report to file:///E:/Android/LintDemo/app/build/outputs/lint-results-debug.html
Wrote XML report to file:///E:/Android/LintDemo/app/build/outputs/lint-results-debug.xml
...

可以看到,Lint完成檢查之後,會在 build/outputs/ 目錄下生成XML和HTML兩種版本的報告。

下圖是HTML版本的Lint報告:

Lint報告.png

根據Lint報告,我們就可以改進程式碼了。

使用Android Studio執行Lint

在Android Studio中,點選 Analyze > Inspect Code…,在彈出的對話方塊中選擇要檢查的範圍,然後點選OK按鈕執行Lint。如下圖所示:

執行Lint.png

Lint完成檢查之後,會在Android Studio介面下方的 Inspection 面板中顯示Lint結果。如下圖所示:

Lint結果.png

根據Lint結果,我們就可以改進程式碼了。

總結

Lint工具可以幫助你檢查可能影響應用質量和效能的程式碼問題。該工具會報告檢測到的每個問題並提供問題的描述資訊和嚴重級別,以便你可以快速地確定需要優先進行哪些改進。在使用Android Studio時,配置的Lint工具和IDE檢查會在你編寫程式碼時自動執行。當然,你也可以手動執行Lint工具。

參考