Search code examples
androidandroid-studiodocumentationproguardobfuscation

How to write android proguard rules?


I want to learn how to write android proguard rules in order to obfuscate the code and make it harder to reverse engineer the app.

I've searched alot for a simple explanation, But can't seem to find something helpful, I read the documentation of the proguard here (https://www.guardsquare.com/en/products/proguard/manual/usage), But I found it very confusing & I didn't understand anything, Also read this doc. (https://developer.android.com/studio/build/shrink-code#obfuscate) but there is nothing more than introduction.

Also searched on Youtube alot, But I found nothing helpful, As well as searching for articles on the internet.

I want a simple explanation that explains what should be written in the proguard rules file, what is Keep & dontwarn .. etc. & how to test the app after obfuscation and how make sure that there will be no errors beacuse of the obfuscation after releasing it on the play store. Thanks in advance.


Solution

  • Though the progaurd introduction & progaurd usage documentation provide brief details about it but few examples for you to help you understand are as below:

    Basically Progaurd by default shrinks and obfuscate all code in your app, but sometimes it might not be needed for us, so we need to describe the necessary -keep options.

    To come up with rules when any library doesn’t supply them or you don't know which classes to keep out of obfuscation?

    Read the build output and logcat:

    Build warnings will tell you which -dontwarn rules to add ClassNotFoundException, MethodNotFoundException and FieldNotFoundException will tell you which -keep rules to add

    To add a @Keep annotation on the whole class or a wildcard rule on all your models:

    -keep class com.somaapp.abc.model.** { *; }
    

    ProGuard will by default remove many code attributes and hidden metadata that are not required for program execution. Some of those are actually useful to the developer — for example, you might want to retain source file names and line numbers for stack traces to make debugging easier:

    -keepattributes SourceFile, LineNumberTable
    

    You can check out the attributes list in the ProGuard manual.

    The Usage section of the progaurd manual describes the necessary -keep options and the Examples section provides plenty of examples.