bilal
bilal

Reputation: 2383

Remove all unused classes,methods from Android Studio project

I have used the lint(Analyze->Inspect Code...) and find out unused methods and resources. All the unused resources removed by Refractor->Remove unused Resources but not found any option like this to remove java classes and methods. Is there any feature in the android studio or any Plugin which can remove all the java classes, the methods which are not used in code to save manual refracting?

Upvotes: 64

Views: 51596

Answers (3)

KursoR
KursoR

Reputation: 1675

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

To run it on whole project go to Code -> 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.

Inspection result

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

Upvotes: 85

ericn
ericn

Reputation: 13103

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 using HashTable or Binary Tree.

I've elaborated more here

Upvotes: 4

user4918296
user4918296

Reputation:

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.

Upvotes: 8

Related Questions