美文网首页
Android Lint 介绍

Android Lint 介绍

作者: 砌墙的民工 | 来源:发表于2017-05-19 10:03 被阅读463次

Lint

Android Studio 提供的静态代码扫描工具。可以在不需要执行应用,也不必编写测试用例的情况先发现并纠正代码结构质量问题。
Lint 工具可以检查 Android 项目源文件是否包含潜在的错误,以及在正确性、安全性、性能、易用性、便利性和国际化方面是否需要优化改进。

Lint 工作流

手动执行 Lint

./gradlew lint

或者点击 Analyze > Inspect Code
在 IDE 中, Lint 发现问题后, 会用黄色突出显示有问题的代码。 对于 Error 级别的问题,会在代码下面添加红色下划线。

修改 Lint 配置

配置 lint.xml 文件

手动在 Android 项目的根目录中添加 lint.xml 文件, 可以针对性的修改每一项 Issue 的配置
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>

查看 lint 支持的完整问题列表, 执行: lint –list

在源文件中配置 Lint

要在 Android 项目中特别禁止 Lint 检查某个 Java 类或方法, 可以添加 @SuppressLint 注解

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

在 Gradle 中配置 Lint 选项

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
  }
}
...

自定义 Lint 规则

由于原生 Lint 缺少一些我们认为必要的检测,我们可以自己开发添加一些符合项目情况 Lint。

创建 Java 工程, 配置 Gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.tools.lint:lint-api:24.5.0'
    compile 'com.android.tools.lint:lint-checks:24.5.0'
}

创建 Detector

public class LogDetector extends Detector implements Detector.JavaScanner {
 
    public static final Issue ISSUE = Issue.create(
            "LogDetector",
            "避免使用 Log/System.out.println",
            "请使用 Logger 组件",
            Category.SECURITY,
            5,
            Severity.WARNING,
            new Implementation(LogDetector.class, Scope.JAVA_FILE_SCOPE)
    );
 
    /**
     * @return 可访问的节点
     */
    @Override
    public List<Class<? extends Node>> getApplicableNodeTypes() {
        return Collections.<Class<? extends Node>>singletonList(MethodInvocation.class);
    }
 
    @Override
    public AstVisitor createJavaVisitor(final JavaContext context) {
        return new ForwardingAstVisitor() {
            @Override
            public boolean visitMethodInvocation(MethodInvocation node) {
                if (node.toString().startsWith("System.out.println")) {
                    context.report(
                            ISSUE,
                            node,
                            context.getLocation(node),
                            ISSUE.getExplanation(TextFormat.TEXT)
                    );
                    return true;
                }
 
                JavaParser.ResolvedNode resolved = context.resolve(node);
                if (resolved instanceof JavaParser.ResolvedMethod) {
                    JavaParser.ResolvedMethod method = (JavaParser.ResolvedMethod) resolved;
                    JavaParser.ResolvedClass containingClass = method.getContainingClass();
                    if (containingClass.matches("android.util.Log")) {
                        context.report(
                                ISSUE,
                                node,
                                context.getLocation(node),
                                ISSUE.getExplanation(TextFormat.TEXT)
                        );
                        return true;
                    }
                }
                return super.visitMethodInvocation(node);
            }
        };
    }
 
}

Scanner 包含多种:

Issue 是由 Detector 发现并报告。

public static final Issue ISSUE = Issue.create(
        "LogDetector", // ID 唯一的值
        "避免使用 Log/System.out.println", // Issue 简介
        "请使用 LoggerUtil.getTripModuleLogger 组件", // 问题描述以及修复建议
        Category.SECURITY, // Issue 类别
        5, // 优先级 1-10, 10 为最严重
        Severity.WARNING, // 严重级别  Fatal, Error, Warning, Information, Ignore
        new Implementation(LogDetector.class, Scope.JAVA_FILE_SCOPE) // 提供 Issue 和 Detector 的映射关系。 Scope 描述 Detector 分析是需要考虑的文件集
);

创建 IssueRegistry

public class SDIssueRegistry extends IssueRegistry {
    @Override
    public List<Issue> getIssues() {
        System.out.println("=============== 开始执行 Lint 检测 ================");
        return Arrays.asList(
                LogDetector.ISSUE,
                ResourceIdDetector.ISSUE,
                LayoutFileNameDetector.ISSUE
        );
    }
}

在 build.gradle 中申明 Lint-Registry 属性

jar {
    manifest {
        attributes "Lint-Registry": "com.xxx.xxx.SDIssueRegistry"
    }
}

集成

方案一

将上述生成的 jar 包拷贝的 ~/.android/lint 目录下。 针对一台机器的所有工程

方案二

将上述生成的 jar 包放到一个 aar 中。 将 aar 通过 compile 的方式集成到工程中。只对工程有效,且不会增加 APK 大小

参考文档

https://developer.android.com/studio/write/lint.html#gradle
http://tech.meituan.com/android_custom_lint.html

相关文章

网友评论

      本文标题:Android Lint 介绍

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