(八)上篇 Android 性能優化 Lint 工具使用

小酌雞湯

青春須早為,豈能長少年。

本文來源《Android 性能優化 全家桶》

為什么通過 lint 檢查改進代碼?

?除了通過構建測試來確保您的應用符合其功能要求之外,您務必還要通過 lint 運行您的代碼來確保代碼不存在結構問題。結構不合理的代碼會影響 Android 應用的可靠性和效率,并使您的代碼更難以維護,而 lint 工具有助于找到這些代碼。
?例如,如果 XML 資源文件包含未使用的命名空間,則不僅占用空間,還會導致不必要的處理。其他結構問題(如使用目標 API 版本不支持的已棄用的元素或 API 調用)可能會導致代碼無法正常運行。 lint 可幫助您解決這些問題。

lint 工具如何處理應用源文件?

Lint工作原理
  • 應用源文件:源文件包含組成 Android 項目的文件,包括 Java、Kotlin 和 XML 文件、圖標以及 ProGuard 配置文件。
  • lint.xml 文件:一個配置文件,可用于指定要排除的任何 lint 檢查以及自定義問題嚴重級別。
  • lint 工具:一個靜態代碼掃描工具,您可以從命令行或在 Android Studio 中對 Android 項目運行該工具
  • lint 檢查結果:您可以在控制臺或 Android Studio 的 Inspection Results 窗口中查看 lint 檢查結果。

現在,就一起實操體驗 Lint ~

(1)lint實操環境(可選項,用自己的環境和代碼也一樣)
  • SamplePop環境如下:
    ?Android Studio 4.0
    ?Gradle version 6.1.1
    ?Android API version 30
(2)從命令行運行 lint
//windows 
gradlew lint

//Linux 或 Mac
./gradlew lint

//如果您只想對某個特定的構建變體運行 lint 任務,則在大寫變體名稱并在其前面加上 lint 前綴
 gradlew lintDebug

//會有如下輸出:
> Task :lint:lint
Ran lint on variant debug: 9 issues found
Ran lint on variant release: 9 issues found
Wrote HTML report to file:///F:/Git/Blog/SamplePop/lint/build/reports/lint-results.html
Wrote XML report to file:///F:/Git/Blog/SamplePop/lint/build/reports/lint-results.xml

?進入文件夾,找到lint-results.html,雙擊這個文件


Lint命令行生成分析結果文件
Lint命令行生成分析結果展示

常見問題可以分為如下幾個大類:

(1)Accessibility 輔助選項,比如ImageView的contentDescription往往建議在屬性中定義等。
(2)Compliance 合規性,違反了Google Play的要求,比如使用了過期的庫版本,性能、安全性、API等級等沒有遵循新系統的要求等。
(3)Correctness 不夠完美的編碼,比如硬編碼、使用過時API等。
(4)Internationalization 國際化,直接使用漢字,沒有使用資源引用等
(5)Interoperability 互操作性,比如和Kotln的交互等。
(6)Performanc 對性能有影響的編碼,比如:靜態引用,循環引用等
(7)Security 不安全的編碼,比如在 WebView 中允許使用 JavaScriptInterface等
(8)Usability 可用的,有更好的替換的 比如排版、圖標格式建議.png格式等

(3)使用獨立工具運行 lint(不實用,忽略即可)
//工具路徑:android_sdk/tools/

//要對項目目錄中的文件列表運行 lint
lint [flags] <project directory>

//例如:
lint --check MissingPrefix myproject 

//查看幫助
lint --help
(4)Lint配置

您可以配置不同級別的 Lint 檢查:

  • 全局(整個項目)
  • 項目模塊
  • 生產模塊
  • 測試模塊
  • 打開的文件
  • 類層次結構
  • 版本控制系統 (VCS) 范圍
(4.1)Android Studio 中配置 Lint(內置的 Lint)
  • 在AS代碼編輯器中的彈出文本查看。lint 發現問題后,會用黃色突出顯示有問題的代碼,而對于更嚴重的問題,則會在代碼下面添加紅色下劃線。
  • 依次點擊 Analyze > Inspect Code 后,在 lint Inspection Results 窗口中查看。
(4.2)配置 lint.xml 文件
//lint.xml文件建議放置在 Android 項目的根目錄下,build.gradle配置如下:
android {
    lintOptions {
        lintConfig file("lint.xml")
    }
}

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

        <!-- 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>

(4.3)配置 Java、Kotlin 和 XML 源文件的 lint 檢查
//1 配置 Java 或 Kotlin 的 lint 檢查
//1.1 停用 lint 檢查,請向該代碼添加 @SuppressLint 注釋
@SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)

//1.2 對 FeedProvider 類中的 ParserError 問題關閉 lint 檢查
@SuppressLint("ParserError")
    class FeedProvider : ContentProvider() {

//1.3 禁止 lint 檢查文件中的所有問題
 @SuppressLint("all")

//2 配置 XML 的 lint 檢查
//2.1  tools:ignore 屬性對 XML 文件的特定部分停用 lint 檢查
//布局文件的 <LinearLayout> 元素中的 UnusedResources 問題關閉 lint 檢查
<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>

//2.2 禁止檢查多個問題,請使用以逗號分隔的字符串列出要禁止檢查的問題
tools:ignore="NewApi,StringFormatInvalid"

//2.3 要禁止 lint 檢查 XML 元素中的所有問題,請使用 all 關鍵字
tools:ignore="all"

(4.4)通過 Gradle 配置 lint 選項
//build.gradle配置如下:
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
    }
}  
(5)創建警告基準

?您可以為項目的當前警告集創建快照,然后將該快照用作將來運行檢查的基準,以便只報告新問題。 有了基準快照,您便可開始使用 lint 讓構建失敗,而不必先返回并解決所有現有問題。
?個人感覺尤其是對多人的項目協同時,此基準特別有用。

//要創建基準快照,請修改項目的 build.gradle 文件,如下所示:
 android {
      lintOptions {
        baseline file("lint-baseline.xml")
      }
    }

//自定義基準:如果要將某些問題類型(而不是全部)添加到基準
android {
      lintOptions {
        check 'NewApi', 'HandlerLeak'
        baseline file("lint-baseline.xml")
       }
    }

?首次添加此代碼行時,系統會創建 lint-baseline.xml 文件以建立基準。此后,lint 工具僅讀取該文件以確定基準。如果要創建新基準,請手動刪除該文件并再次運行 lint 以重新創建它。

Lint生成警告基準

?實行基準時,您會收到一條信息性警告,告知您一個或多個問題已被過濾掉,因為它們已在基準中列出。之所以發出這條警告,是為了幫您記住您已配置基準,因為理想情況下,您希望在某一時刻解決所有問題。

Lint警告基準的已過濾警告提示
(6)手動運行檢查

?您可以通過依次選擇 Analyze > Inspect Code,手動運行配置的 lint 及其他 IDE 檢查。檢查結果將顯示在 Inspection Results 窗口中。
?追求細節請查閱文章末尾的谷歌官網(最全最詳細)。

Lint設置檢查范圍和配置文件
Lint手動運行檢查結果展示
趕緊對自己的項目代碼實操開始吧~ 會有驚喜~

小編的擴展鏈接

參考鏈接

姿容清麗厭奢華,淡淡平平不自夸

?

舉手之勞,贊有余香!???比心??

?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。