Static Code Analysis using FindBugs (Android Studio)

There are many techniques, procedures and tools that can contribute to the quality of the source code your team produces.  One of those techniques is static code analysis and if you are using Android Studio you are probably using at least one tool for this already, Android Lint.  Lint is an very high quality tool that will not only give your Java source code the once over, but also your XML files, including layouts. It has deep knowledge about Android development patterns and it evolves with each SDK release, it should be the first stop for static code analysis in Android.  Every developer should pay attention when Android Lint waves that little yellow flag at you.

No matter how good Android Lint is, it is always worthwhile having a second and third opinion from different tools.  FindBugs is not an alternative to Android Lint, but it can be used as a companion. It is an open source tool that performs static analysis of your Java bytecode to warn of potential bugs, defects, security and performance issues.  It knows nothing about Android and is not a panacea for poorly designed apps, but it can provide a little nudge in the direction of potential issues in your software. As with all tools in this space it will never have a 100% strike rate, but it does allow the developer to take another look and think twice about a piece of code.

When an issue arises you will get a warning that is placed into one of nine different buckets. They are:

  • Dodgy code
  • Malicious code vulnerability
  • Bad practice
  • Correctness
  • Internationalization
  • Security
  • Performance
  • Multi-threaded correctness
  • Experimental

Each of these can be disabled if not required and you can also configure the confidence level at which issues will be reported.

Using FindBugs in the Android Studio IDE

Android Studio is built from the IntelliJ Java IDE which allows it to use IntelliJ plugins.  This is how you can integrate FindBugs into your Android Studio environment.

To open the IDE plugins go to the settings page (File > Settings…), and find the Plugins menu.  From here you can browse plugin repositories and do a search for FindBugs, or you can download the FindBugs plugin and install it manually from file.  When searching for the plugin you may find references to the QA Plug plugin.  This is another plugin that includes FindBugs and another way to get access to FindBugs from within your IDE and as a bonus it also includes other code analysis tools such as CheckStyle and PMD.

Executing FindBugs Analysis

Your code must have been built before analysis as FindBugs operates on the generated bytecode.  You can start the FindBugs analysis from within Android Studio by going to the Analyze menu, selecting FindBugs and then selecting the scope of the analysis to perform.  If you are using FindBugs through the QA Plug, you can access it from the Tools menu.

Exclude filters for Android

On first run of FindBugs you may be quite disappointed with the results.  With the default confidence level and no filters set FindBugs will report many issues that are part of the automatically generated android code to support functionality such as accessing resources.  For example, you may get many warnings similar to the these:

The class name R$dimen doesn't start with an upper case letter
The class name R$drawable doesn't start with an upper case letter

Take a look at the FindBugs manual for the specification of the filter format and details how you can create an exclude filter. For a filter that stops the warnings from Android auto generated code use the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
    <Match>
        <!-- ignore all issues in resource generation -->
        <Class name="~.*\.R\$.*"/>
    </Match>
    <Match>
        <Class name="~.*\.Manifest\$.*"/>
    </Match>
</FindBugsFilter>

Another issue you may hit are FindBugs warnings for JUnit tests. This can also be handled in the exclude filter file by adding the following:

<!-- ignore all bugs in test classes, except for those bugs specifically relating to JUnit tests -->
<Match>
    <Class name="~.*\.*Test" />
    <!-- test classes are suffixed by 'Test' -->
    <Not>
        <Bug code="IJU" /> <!-- 'IJU' is the code for bugs related to JUnit test code -->
    </Not>
  </Match>

This filter can be added to your Gradle build file for the automated builds discussed later, but for manually executed analysis you can add the filter in Android Studio. Go to settings dialog (File > Settings…) and select FindBugs-IDEA. Here you can configure the plugin settings and add the exclude filter list from an XML file.

findbugs_options

Run FindBugs again and you will have no one to blame except your team for the issues that are reported.

Automating FindBugs

Like other parts of the development process you can automate this static analysis. Gradle has support for the FindBugs plugin. To create a Gradle task you can add the following to the gradle.build in your project:

apply plugin: 'findbugs'

task findbugs(type: FindBugs) {
    ignoreFailures = false
    effort = "default"
    reportLevel = "medium"
    excludeFilter = new File("${project.rootDir}/findbugs/findbugs-filter.xml")
    classes = files("${project.rootDir}/app/build/intermediates/classes")
    source = fileTree('src/main/java/')
    classpath = files()
    reports {
        xml.enabled = true
        html.enabled = true
        xml {
            destination "$project.buildDir/findbugs/findbugs-output.xml"
        }
        html {
            destination "$project.buildDir/findbugs/findbugs-output.html"
        }
    }
}

Visit https://gradle.org/docs/current/dsl/org.gradle.api.plugins.quality.FindBugs.html for more information about configuring FindBugs in Gradle.

Conclusion

If your team doesn’t enforce clean Android Lint builds for your projects then stop looking at other tools now.  It should be your first line of defence for code quality standards.  If your lint pane is boringly empty then maybe it is time for another tool to give its opinion.  This is not a must have tool for every Android developer, but it does have its value.  It may only need to pick up a lazy security flaw once to make the configuration and automation time worthwhile.

References

FindBugs home http://findbugs.sourceforge.net/

FindBugs Intellij Plugin https://plugins.jetbrains.com/plugin/3847?pr=idea

Gradle FindBugs Plugin https://gradle.org/docs/current/userguide/findbugs_plugin.html

5 Comments

Filed under Android SDK, Android Studio, Automation, Gradle, Performance, Security, Tools

5 responses to “Static Code Analysis using FindBugs (Android Studio)

  1. Thanks, this filters were so usefull

    Liked by 1 person

  2. swaroop bapat

    Thanks for this article on findbugs.i have a query related to build.gradle and gradle.build files,are these two files are same or different? and is there any way we can get to know that our build.gradle file is executing findbugs plugin

    Like

    • Thanks swaroop, ‘gradle.build’ is a typo and it should be ‘build.gradle’. I will fix it up shortly.

      You can confirm if the findbugs plugin is being executed by checking the destination folder you specify for the output report.

      Like

  3. Srini

    Thnaks. very good info.

    Like

  4. Pingback: Static Code Analysis using FindBugs (Android Studio) | shebella1014

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s