Adding and integrating custom lint rules in your android app.

It’s difficult to find info regarding adding and integrating custom lint rules in your android application. Penning down the way I did it for my app.

Adding Custom Lint Rules

You will have to create custom lint rules as a separate java project.

Android lint API provides multiple Detectors like ResourceXmlDetector, PropertyFileDetector, FragmentDetector etc which will help you target any particular type of file in your android app. Its very extensive and the source is easy to read.

To add your own rule, extend your own detector with one of the lint Detector classes and create the type of Issue which you are going to report.

BaseActivityDetector

Detector class lets you override multiple methods like getApplicableMethodNames(),  getApplicableElements(),  getApplicableNodeTypes() etc which help you chose the exact type of element on which you want to apply your lint rule.

SelectedElement

After that you can implement the Scanner to detect for Correctness.

Integrating Custom Lint Rules with the Android Application

There are multiple ways of doing this:

  1. Assemble your lint rules to lint.jar and add it to $HOME/.android/lint/lint.jar. This is the easiest method but its not good when multiple developers are working on the same app and distribution is required. Every dev machine will have to manually copy the jar and place it in their local boxes as well as the CI.
  2. gradle lint task looks for explicit lint jars in two places, one is $HOME/.android/lint as stated above and next you can set the path of your lint.jar to ANDROID_LINT_JARS. It can be added to gradlew script and pushed to the VCS, so that its available to all dev machines and CI agents.
  3. Some posts have also mentioned that you can bundle your lint project as an AAR application and add it as a dependency to your android app. This will run the AAR’s lint as part of the main gradlew lint.

I tried the third one but it never worked for me. Other drawback of it is creating the .aar file, for which there is no proper documentation available. The easiest way of integrating is the second approach and is good for distributed teams as well.

A working project with Custom lint rules and Custom Lint Demo can be seen here and here respectively.

Leave a comment