使用Lint

作者: cxlin007 | 来源:发表于2016-09-29 15:23 被阅读215次

    Lint是Android Studio提供的一个代码静态扫描工具,可以分析出项目中潜在的bug。

    Lint配置

    在Android Studio中通过Settings>Editor>Inspections,可以查看Lint的配置,并且可以修改其等级和作用范围。

    Paste_Image.png

    Lint执行

    1、在构建时执行
    在build.gradle文件中添加lintOptions

    android { 
     lintOptions { 
     // true--关闭lint报告的分析进度
     quiet true
     // true--错误发生后停止gradle构建
     abortOnError false
     // true--只报告error
     ignoreWarnings true
     // true--忽略有错误的文件的全/绝对路径(默认是true)
     absolutePaths true
     // true--检查所有问题点,包含其他默认关闭项
     checkAllWarnings true
     // true--所有warning当做error
     warningsAsErrors true
     // 关闭指定问题检查
     disable 'TypographyFractions','TypographyQuotes'
     // 打开指定问题检查
     enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
     // 仅检查指定问题 check 'NewApi', 'InlinedApi'
     // true--error输出文件不包含源码行号
     noLines true
     // true--显示错误的所有发生位置,不截取
     showAll true
     // 回退lint设置(默认规则)
     lintConfig file("default-lint.xml")
     // true--生成txt格式报告(默认false)
     textReport true
     // 重定向输出;可以是文件或'stdout'
     textOutput 'stdout'
     // true--生成XML格式报告
     xmlReport false
     // 指定xml报告文档(默认lint-results.xml)
     xmlOutput file("lint-report.xml")
     // true--生成HTML报告(带问题解释,源码位置,等)
     htmlReport true
     // html报告可选路径(构建器默认是lint-results.html )
     htmlOutput file("lint-report.html")
     // true--所有正式版构建执行规则生成崩溃的lint检查,如果有崩溃问题将停止构建
     checkReleaseBuilds true
     // 在发布版本编译时检查(即使不包含lint目标),指定问题的规则生成崩溃
     fatal 'NewApi', 'InlineApi' 
     // 指定问题的规则生成错误
     error 'Wakelock', 'TextViewEdits'
     // 指定问题的规则生成警告
     warning 'ResourceAsColor'
     // 忽略指定问题的规则(同关闭检查)
     ignore 'TypographyQuotes'
     }
    }
    

    xmlReprt true:会把结果生成为一个html,在buidl>outputs目录下
    check ‘NewApi’:可以指定检查的配置名称
    2、选中文件后右击Analyze>Inspect code,对选中的文件执行lint扫描


    Paste_Image.png

    还可以选择检查的范围和检测配置
    3、选中文件后右击Analyze>Run Inspection by name,对选中的文件指定特定的扫描规则。

    Paste_Image.png

    4、通过指令来执行

    配置lint检查

    1、java代码中通过添加注解@SuppressLint来禁用lint检查

    @SuppressLint("NewApi")
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    ...    
    }
    

    2、在布局文件中设置

    <RelativeLayout
        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="UnusedResources">
    

    添加tools:ignore属性设置,来静止lint检查

    常用的Lint检查

    Unused resources : 检查未使用的资源

    相关资料

    https://developer.android.com/studio/write/lint.html
    http://www.carrotsight.com/2016/01/29/%E6%B5%85%E8%B0%88Android%E8%87%AA%E5%AE%9A%E4%B9%89Lint%E8%A7%84%E5%88%99%E7%9A%84%E5%AE%9E%E7%8E%B0%20%EF%BC%88%E4%B8%80%EF%BC%89.html

    相关文章

      网友评论

        本文标题:使用Lint

        本文链接:https://www.haomeiwen.com/subject/itbtyttx.html