18

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)?

2
  • 1
    You should put those kinds of files into your assets folder and load like mWebView.loadUrl("file:///android_asset/myfriend.png");
    – Robby Pond
    Jun 8, 2011 at 14:33
  • Your are right. I moved the images to the 'assets' folder which solved my problem. The line above becomes: <img src="file:///android_asset/myfriend.png">
    – Gilbou
    Jun 8, 2011 at 14:54

3 Answers 3

40

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$*
2
  • Giving exception in proguard cfg when generating signed apk Mar 17, 2016 at 7:40
  • @ninniuz I tried the above code spippet, except with **.R$Drawable* and it didn't work. Why does **.R$* work but the perviously mentioned method doesn't?
    – Matt Strom
    Jul 29, 2021 at 19:29
3

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

<img src="file:///android_asset/myfriend.png">
0

For localized simple htmls (no linked localized local files/images)

Use this Proguard rule for raw folder:

-keep class com.example.appname.R$raw { *; }

Example Url for WebView:

file:///android_res/raw/filename.html

Example folder structure:

res/raw/filename.html

res/raw-en/filename.html

res/raw-hu/filename.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.