[摘要] 好的代码不仅要能高效的完成功能的实现,还得经得起时间和tester的考验,lint的忽然露面,让程序员写的代码不能再像以前那样随心所愿~
一.什么是Lint?
根据Android官网的介绍,lint是android推荐的开发IDE Android Studio提供的一款静态代码识别工具。目的是通过Android官方规定的一系列代码标准规则,帮助开发者在不运行app或者写测试case的情况下识别并纠正警告和错误。这个工具会为每一个识别到的错误或者警告用一个描述性的消息和严重程度报告出来,这样攻城狮们就可以快速的首先去优化严重程度比较高的项。当然,有些项也可以不用修改,这时候,就需要在相应的lint.xml里面ignore这些检查项。
二. Lint的检查项
从上图可以看出,lint会结合每个app下的lint.xml(如果存在的话)的声明来对app源码进行扫描,得出的是一个html文档,里面会对检查出的Error和Warning进行分类,我们可以直接打开,如下图这样(packages/app/Tag 用lint检查扫描出来的report截图):
下面简单的对lint中的一些检查项作一个介绍。
Lint Report 一共分为两部分:
第一部分是对检查出来的问题进行一个总体的统计(蓝线Correctness以上的部分)
第二部分是具体的每个问题的详情(蓝线Correctness以下的部分)
Lint Check会有两种典型的标签:
1.categories : 在上面中显示出来的就是Correctness, Performance, Usability:Icons 等这些。
2.issue : 即是每个category下面具体的项,例如 UsesMinSdkAttributes, InlinedApi等。
Lint Check会对每种issue用两种类型的符号标注:
三角形的灰色感叹号表示warning, 红色感叹号表示error。
因为上面只贴出了部分报告的截图,有些category和issue部分同学不清楚,我们可以通过运行以下命令查看全部。
lint --list
(项目太多,这里就不贴出来了)
三. 如何生成Lint Report
其中 lint --html是以html格式生成报告,~/lint_check.html, 因为在linux里面,~表示根目录,所以这块表示在根目录下生成lint_check.html文件。
执行完上面的操作,terminal中会打出类似下面的额信息提示(我这里是保存到1.html),然后就可以去根目录下去找到生成的同名html文件,打开就像上面截图那样。
四. 如何“干掉”Lint报的各种warning和error
<!-- Disable InlinedApi check under Tag app -->
<issue id="InlinedApi" severity="ignore" />
对于其中的另一些些项,可能我们只需要在某一个指定的文件里面不去检查,其他的文件照旧要去check,这时候我们可以按照下面的形式去做。
<!-- Disable UnusedResources check in the specified file -->
<issue id="UselessParent">
<ignore path="res/layout/tag_viewer.xml" />
</issue>
我们指定了ignore的path为一个xml,所以这个xml就会在lint的检查中被忽视。
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="UsesMinSdkAttributes" severity="ignore" />
<!-- Disable Calling new methods on older versions check under Tag app -->
<issue id="NewApi" severity="ignore" />
<!-- Disable InlinedApi check under Tag app -->
<issue id="InlinedApi" severity="ignore" />
<!-- Since Tag is a system app, disable this check -->
<issue id="ProtectedPermissions" severity="ignore" />
<issue id="MissingPrefix">
<ignore path="AndroidManifest.xml" />
</issue>
<issue id="ContentDescription" severity="ignore" />
<!-- Disable AllowBackup/FullBackupContent Problems check under Tag app -->
<issue id="AllowBackup" severity="ignore" />
<!-- Disable UnusedResources check in the specified file -->
<issue id="UnusedResources">
<ignore path="res/values/strings.xml" />
</issue>
<!-- Disable Overdraw check in the specified file -->
<issue id="Overdraw">
<ignore path="res/layout/tag_divider.xml" />
</issue>
<!-- Disable UnusedResources check in the specified file -->
<issue id="UselessParent">
<ignore path="res/layout/tag_viewer.xml" />
</issue>
<issue id="IconMissingDensityFolder" severity="ignore" />
<issue id="GoogleAppIndexingWarning" severity="ignore" />
</lint>
当所有的自定义规则都加入到lint.xml,这时候我们再次运行上面的检查命令,就会发现所有的error和warning都不见了,大功告成!