Remove all unused classes,methods from Android Studio project

JavaAndroidAndroid Studio

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Inspection result

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

Solution 2 - Java

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.

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbilalView Question on Stackoverflow
Solution 1 - JavaKursoRView Answer on Stackoverflow
Solution 2 - Javauser4918296View Answer on Stackoverflow
Solution 3 - JavaericnView Answer on Stackoverflow