继 ToYonos 回答(2018 年 10 月 9 日)之后;将此用于 Android Studio 3.4 及更高版本:
项目/build.gradle
buildscript {
repositories {
google()
jcenter()
maven {
url 'https:// maven url 1'
}
maven {
url "https://plugins.gradle.org/m2/" // Add this, for SpotBugs
}
}
dependencies {
classpath '...'
// If you're using gradle 6.x, add this to use SpotBugs app version 4.0.2
classpath "gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:4.3.0"
// If you're using gradle 4.x or 5.x, add this to use SpotBugs app version 3.1.2
classpath "com.github.spotbugs:spotbugs-gradle-plugin:2.0.1"
}
}
项目/应用程序/build.gradle
apply plugin: 'com.android.application'
apply plugin: '...'
apply plugin: "com.github.spotbugs" // <- Add this
dependencies {
...
}
// This block is only needed for gradle 4/5 only.
// It's for SpotBugs to create a 'spotbugsMain' gradle task.
sourceSets {
main {
java.srcDirs = []
}
}
spotbugs {
ignoreFailures = true
reportsDir = file("$project.buildDir/SpotBugsReports")
effort = "max"
reportLevel = "high"
}
// Note: gradle 4/5 should use "com.github.spotbugs.SpotBugsTask"
tasks.withType(com.github.spotbugs.snom.SpotBugsTask) {
dependsOn 'assembleDebug'
classes = files("$project.buildDir/intermediates/javac") // Important to use this path
excludeFilter = file("$project/spot-bugs-exclude.xml") // Optional - Explained below
source = fileTree('src/main/java') // Only needed on gradle 4/5
reports {
// Enable HTML report only
html.enabled = true
xml.enabled = false
}
}
您可以通过运行 gradle 任务为您的调试构建生成报告:
对于 gradle 6.x:./gradlew spotbugsDebug
对于 5 级或 4 级:./gradlew spotbugsMain
使用 很重要classes = files("$project.buildDir/intermediates/javac")
,否则你会得到一个错误"java.io.IOException: No files to analyze could be opened"
——见Findbugs failed with "java.io.IOException: No files to analyze could be open"
您还需要启用 HTML 报告并禁用 XML 报告,以查看人类可读的格式。
ignoreFailures = true
是可选的。当 SpotBugs 检测到代码警告时,默认情况下它将以"BUILD FAILED"
+ 报告文件结尾。设置ignoreFailures = true
意味着 gradle 任务将以"BUILD SUCCESSFUL"
+ 报告文件结束。
要从分析中排除某些生成的类,请设置一个excludeFilter
. 对于示例排除文件,请在此处或此处查看(与 findbugs-exclude.xml 相同)
更多信息和教程在这里:https ://mikedemaso.com/tech/2020-06-10-spotbugs-gradle-plugin-android/