Remove all unused classes,methods from Android Studio project

前端 未结 3 1755
遇见更好的自我
遇见更好的自我 2021-01-31 14:48

I have used the lint(Analyze->Inspect Code...) and find out unused methods and resources. All the unused resources removed by Refractor->Remove unused R

相关标签:
3条回答
  • 2021-01-31 15:30

    This can be achieved by using the built-in inspection Java | Declaration redundancy | Unused declaration.

    To run it on whole project go to Analyze -> Run inspection by name..., type Unused declaration and select desired scope. Then carefully check output and mark some classes as entry points if needed.

    Now you can select Unused declaration node in list and perform Safe delete action on all unused declarations at once.

    For Kotlin there is similar inspection Kotlin | Redundant constructs | Unused symbol.

    0 讨论(0)
  • 2021-01-31 15:31

    Step 1

    Generate usage.txt and mapping.txt with Proguard or R8

    • Add -printusage to your proguard.pro file Run

    • ./gradlew app:minifyReleaseWithProguard or ./gradlew app:minifyReleaseWithR8

    Step 2

    Find class name records that is in usage.txt but not in mapping.txt, those are the unused classes that are removed by Proguard/ R8 It's not hard to write such algorithm but you can consider my approach using Binary Search Tree here

    0 讨论(0)
  • 2021-01-31 15:37

    Android ships with ProGuard and can do what you want. If you are using Gradle as build system then you can add the following lines in your build.gradle file:

    android {
    
        // ... other configurations
    
        buildTypes {
            release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt')
                signingConfig signingConfigs.release
            }
            debug {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules-debug.pro'
            }
        }
    }
    

    Your proguard-rules-debug.pro file only needs to contain one line

    -dontobfuscate
    

    With this additions your release build will get shrunk and obfuscated, your debug build, however, will get only shrunk, i.e, unnecessary code is removed. Note, that ProGuard operates on the build and not the source code.

    The ProGuard FAQ has some more information of what it can do.

    0 讨论(0)
提交回复
热议问题