Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid unused resources and code from an Android Library Project getting into my APK?

I have an Android Library Project in my Eclipse workspace, that I use as a unique toolbox. By chance(1), I just discovered that resources from the library (xml animations, xml layouts, even drawables!!!) are packed into the APK's of the projects that use the library, even if I don't use them.

After reading Does android always package unused resources?, I wonder if it's normal. How can I avoid this? Is the only way having different library projects?

EDIT: I've found, decompiling the .dex, that unused code too makes it into the apk.

(1) I was trying to test a new icon for my app, /res/drawable/icon.png, but the default icon would keep appearing. I removed the image and it kept showing the default icon! It had to be the /res/drawable-mdpi/icon.png from the library.

like image 708
bigstones Avatar asked Apr 06 '11 00:04

bigstones


People also ask

How do I get rid of unused resources?

In Android Studio Menu > Refactor > Remove Unused Resources... Select the resources you want to remove. You can exclude resources you want to keep by right-clicking on the resource item. Use Do Refactor to remove all Resources at once.

Which remove resources that ProGuard flagged as unused?

It is important to note that removing unused resources requires the minifyEnabled flag to be set. This flag (as mentioned in Removing unused code) will trigger ProGuard to remove code paths that aren't being used by your application. This is an important step in the removal of resources from included libraries.

What is Android library project?

Android Library: This type of library can contain all file types supported in an Android project, including source code, resources, and manifest files. The build result is an Android Archive (AAR) file that you can add as a dependency for your Android app modules.


1 Answers

The new Android build system has a resource stripping mechanism built in that can be run as a final step on the build process. Use it in addition to removing resources that lint identifies.

Note that the resource stripping mechanism is particularly useful in conjunction with Proguard (also bundled with the build system) and when you're using libraries in your project. The idea is:

  • Proguard removes classes that you're not using, including those that came from libraries.
  • The above process can delete code references to resources included with those libraries.
  • Those unreferenced resources can thus be stripped from the APK, because there's no code that uses them anymore.

Removing unused resources that lint identifies is still useful because removing them:

  • Speeds up your build
  • Reduces your project's maintenance burden.
like image 136
Fabian Tamp Avatar answered Sep 23 '22 22:09

Fabian Tamp