Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Proguard to remove specific drawables

In my Android project, I have some images stored in res/drawable/ which are accessed only from an HTML file loaded in a Webview. For example (code in HTML):

<img src="file:///android_res/drawable/myfriend.png">

These images are removed by Proguard from apk during optimization.

Does somebody know a way to keep these files (even if they are not used directly in the java code)?

like image 558
Gilbou Avatar asked Jun 08 '11 14:06

Gilbou


People also ask

How to enable ProGuard in Android Studio?

To enable ProGuard, I first need to update the build.gradle configuration file. The user’s guide proposes the following configuration: 1. Disable R8 in gradle.properties file android.enableR8=false android.enableR8.libraries=false 2. I substitute the module with the latest ProGuard version (currently 7.0.1) in root build.gradle:

What does ProGuard remove from code?

Debugging and stack traces. 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:

Does ProGuard not work on XML files?

In general Proguard does not work on xml files, only Java. So I think your build is some how corrupting your file. Perhaps opening a new project and copy there your source and the .git file (if you got one) will help

What is inside ProGuard-Android-optimize?

Now, let’s see what is inside proguard-android-optimize.txt This optimized ProGuard rule file contains three extra rules which focus more primarily on extra optimization of the R8 shrinking. As you can see it has added these three new rules and removed -dontoptimize which disables the optimization.


2 Answers

I had a similar issue and wanted to add just a few bits.

The resources ARE NOT stripped away by ProGuard. If you simply unzip your apk you will see that the image files are still there.

The problem is that the Webkit FileLoader will try and load your R$drawable class using reflection. If you do not add any keep rule to your proguard.cfg file that class will be renamed, hence Webkit will not be able to load your resource.

By placing the file into the assets folder your are bypassing the R class system and everything will work.

This is not a solution though if, for example, you want to use different resources for different densities.

I suggest you simply add a very basic keep rule to preserve R inner classes and fields:

-keepclassmembers class **.R$* {
    public static <fields>;
}

-keep class **.R$*
like image 151
ninniuz Avatar answered Oct 19 '22 20:10

ninniuz


I moved the images to the 'assets' folder which solved my problem:

<img src="file:///android_asset/myfriend.png">
like image 21
Gilbou Avatar answered Oct 19 '22 19:10

Gilbou