close

Source: http://www.cnblogs.com/everhad/p/5679728.html

1 lint簡介

1.1 概述

lint是隨Android SDK自帶的一個靜態代碼分析工具。它用來對Android工程的源文件進行檢查,找出在正確性、安全、性能、可使用性、可訪問性及國際化等方面可能的bugs和可優化提升的地方。

1.2 lint工作流程

針對我們的項目,通過lint.xml配置lint分析的選項,執行檢查后,會針對要分析的issue生成報告。

Figure 1. Code scanning workflow with the lint tool

2 lint使用

有關lint的使用,有以下地方需要理解:

2.1 分析的范圍

要對Android項目進行靜態分析,首先就是指定要分析的源文件的范圍。包括以下方面:

  1. 整個工程或模塊。
  2. 目錄和文件。
  3. xml和java文件中使用標簽和注解來忽略檢查。
  4. lint檢查結果分warning和error兩個等級,可以忽略warning問題。

2.2 檢查的方面

lint工具提供了對代碼的一系列不同方面的問題進行檢查的功能。每一個問題(issue)都有它唯一的id。這些issue是分類的。
可以通過為工程配置lint.xml來指定要分析哪些方面的問題:
每個issue一個標簽,可以指定它的嚴重性(severity)為ignore、error、warning等:
下面是一個lint.xml的示例:

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

在xml和java文件中,也可以禁用lint檢查:

  • To disable lint checking for a specific Java class or method, use the @SuppressLint annotation.
  • To disable lint checking for specific sections of your XML file, use the tools:ignore attribute.

2.3 生成報告

lint分析完成后,可以生成xml、html格式的文檔。文檔具體指出了代碼在不同方面所發現的問題,每個問題項都指出了在源文件的位置和問題描述。

3. 在Android Studio中使用

lint提供了命令行接口,所以可以作為單獨工具被使用,或者集成到ide的構建流程中去。
在Android Studio中,通過菜單或者在Project視圖以及代碼視圖中的右鍵菜單中選擇Analyze > Inspect Code就可以打開lint檢查的對話框Specify Inspection Scope,在這里設置好要進行代碼分析的范圍,確定后工具就開始對代碼進行檢查了,完成后會自動打開Inspection工具窗口。
下圖,左邊是分類了的問題,選中一個問題后,右邊是針對此問題的詳細說明。
Location指出了發生問題在源文件的位置,Problem synopsis問題概要給出了此問題的解釋,可以看到,在MaterialHeader類的源文件的21行,字段mPtrFrameLayout可以被轉換為局部變量使用。(局部變量具有更快的訪問速度,而且更精確的變量范圍具有更好的維護性)

在Android Studio生成lint報告后,可以在Inspection工具窗口中快速定位到代碼位置,就像logcat工具窗口那樣,在下圖右邊,Problem resolution標題下有“Convert to local”的連接,點擊后可直接將當前問題修復!
Inspection窗口左邊的工具欄,可以Export當前的分析結果為xml或html文件。

Inspection工具窗口

小結

使用lint進行代碼的檢查和分析十分簡單高效,在發布版本前,使用lint對工程進行優化,何樂而不為。

  • 參考
    sdk文檔路徑:Develop > Tools > Workflow > Debugging > Improving Your Code with lint.
    文件目錄:/sdk/docs/tools/debugging/improving-w-lint.html

(本文使用“小書匠”編輯)


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AutoPoster 的頭像
    AutoPoster

    互聯網 - 大數據

    AutoPoster 發表在 痞客邦 留言(0) 人氣()