정적 코드 분석 및 런타임 점검으로 안드로이드 코드 품질 향상 :
새 프로젝트를 만들 때 이러한 점검을 추가하고 모든 체크인의 문제를 해결하는 것이 좋습니다 (지속적인 통합 프로세스의 일부로). 그렇지 않으면 대량의 오류를 직면하고 수정할 때 엄청난 용기와 인내가 필요합니다.
build.gradle 에 다음 줄을 추가하십시오. 그레이드 : apply from: '../quality/static_analysis.gradle'
git remote add analysis https://github.com/BrianSpace/Android-Quality-Essentials.gitbuild.gradle : apply from: '../analysis/quality/static_analysis.gradle'
android {
...
lintOptions {
// Turn off analysis progress reporting by lint
quiet true
// Stop the gradle build if errors are found
abortOnError true
// Do not ignore lint warnings
ignoreWarnings false
// Treat warnings as errors
warningsAsErrors true
// Ignore rules list
ignore 'GoogleAppIndexingWarning' // Remove this if the app support App Indexing
}
...
}
build.gradle : LeakCanary의 종속성 추가 : dependencies {
.. .
debugCompile ' com.squareup.leakcanary:leakcanary-android:1.5.1 '
releaseCompile ' com.squareup.leakcanary:leakcanary-android-no-op:1.5.1 '
testCompile ' com.squareup.leakcanary:leakcanary-android-no-op:1.5.1 '
.. .
}Application 클래스에서 (그리고 매니페스트에 추가하는 것을 잊지 마십시오) : public class AndroidQualityEssentialsApplication extends Application {
@ Override
public void onCreate () {
super . onCreate ();
if ( BuildConfig . DEBUG ) {
StrictMode . setThreadPolicy ( new StrictMode . ThreadPolicy . Builder ()
. detectAll ()
. penaltyDeath ()
. build ());
StrictMode . setVmPolicy ( new StrictMode . VmPolicy . Builder ()
. detectAll ()
. penaltyDeath () // If violations are in Android itself or 3rd-party libs, use penaltyLog.
. build ());
// Avoid the process dedicated to LeakCanary for heap analysis.
if (! LeakCanary . isInAnalyzerProcess ( this )) {
LeakCanary . install ( this );
}
}
...
}
}gradlew check 실행하십시오.static_analysis.gradle 을 적용하는 프로젝트의 build/reports/ 디렉토리에 있습니다. 스타일 규칙에 정의 된 이름 지정 컨벤션은 "mmember"와 같은 멤버 필드 이름에 대한 단일 문자 접두사를 허용하지 않습니다. 그러나이 스타일이 마음에 들면 MemberName 모듈의 format 속성을 "^[az] [a-za-z0-9] $"로 변경할 수 있습니다. 또는 "m"접두사를 강제하기 위해 "^m [az] [a-za-z0-9] $"로 변경하십시오 .
PMD Rule useUtilityClass의 경우 클래스에 정적 필드와 메소드 만있는 경우 유틸리티 클래스를 생성하라는 메시지가 표시됩니다. 당신은 다음과 같습니다.
public final class FileUtil {
private static Context appContext ;
private FileUtil () throws InstantiationException {
throw new InstantiationException ( "Utility class FileUtil should not be instantiated!" );
}
public static void init ( final Context context ) {
appContext = context . getApplicationContext ();
}
/**
* Get available cache directory. Prefer external over internal.
*/
@ NonNull
public static File getAvailableCacheDir () {
final File externalCacheDir = appContext . getExternalCacheDir ();
return externalCacheDir == null ? appContext . getCacheDir () : externalCacheDir ;
}
}모든 정적 분석 규칙은 사람들의 과거 경험의 모범 사례이지만, 항상 깨질 수없는 진실은 아닙니다. PMD 규칙 중 일부는 자신의 선호도를 기반으로해야합니다.
ItemTypeT 로 "t"문자로 더 의미있는 이름을 선호합니다. 단일 문자 이름을 좋아하는 경우 "제외"목록에서 제거 할 수 있습니다. 이름 지정 규칙은 품질/checkstyle/naming_convention.xml 파일로 정의됩니다. 다음 규칙은 정의됩니다.
자신의 프로젝트에 필요한 경우 정규식을 수정할 수 있습니다. 이름 지정 컨벤션 만 확인하려면 gradlew checkFileNames 실행하십시오.
CheckStyle은 Java 코드 스타일을 확인하는 데 사용됩니다. 스타일 규칙은 다음과 같은 변경 사항이있는 Google Java 스타일 가이드를 기반으로합니다.
코드 스타일 만 확인하려면 gradlew checkCodeStyle 실행하십시오. 타사 코드와 같은 일부 파일을 제외하려면 static_analysis.gradle 파일에서 checkCodeStyle 작업에서 exclude 항목을 추가 할 수 있습니다.
FindBugs 버그가 발생할 수있는 패턴에 대해 코드를 스캔합니다. 분석에서 제외 될 파일은 여기에 정의되어 있습니다. FindBugs 만 실행하려면 gradlew findBugs 실행하십시오.
PMD는 일반적인 프로그래밍 결함을 감지 할 수있는 정적 코드 분석기입니다. 규칙은 품질/pmd/pmd-ruleset.xml로 정의됩니다. 규칙의 전체 목록은 여기에서 찾을 수 있습니다. PMD 만 실행하려면 gradlew pmdCheck 실행하십시오.
Android Lint는 Android 특정 정적 코드 분석 도구입니다. 수표의 전체 목록은 여기에 있습니다. 보풀 규칙 만 실행하려면 gradlew lint 실행하십시오.
StrictMode는 UI 스레드 및 리소스 누출에서 느린 작업을 감지하는 데 매우 유용합니다. 구체적으로, ThreadPolicy는 UI Thead에서 디스크/네트워크 I/O 및 느린 작동을 감지하는 반면 VMPolicy는 자원 누출을 감지합니다. 자세한 내용은 ThreadPolicy.builder 및 Vmpolicy.builder의 문서를 참조하십시오
LeakCanary는 메모리 누출을 감지하는 데 도움이 될 수 있습니다. 누출을보고하고 전체 참조 체인을 표시하여 누출을 고정 할 위치를 쉽게 찾을 수있는 매우 좋은 UI가 있습니다.
The MIT License
Copyright (c) 2017-2017 AndroidQualityEssentials project contributors
https://github.com/BrianSpace/AndroidQualityEssentials/graphs/contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.