Search code examples
androidandroid-mediaplayerproguardshrinkresources

Android: How to tell ShrinkResources to keep certain resources


I have an mp3 and an ogg file in my res/raw folder which I used with Android Media Player. I used setDataSource like so

musicPlayer.setDataSource(context, Uri.parse("android.resource://com.me.myapp/" + R.raw.music));

This works fine when running from Android Studio, however, when exporting a signed APK with shrinkResouces enabled, it strips out the mp3 (as mentioned above, I also have an ogg file which I use in the same way and which also gets stripped out). Here is the associated results in the Resouces.txt file:

Skipped unused resource res/raw/music.mp3: 485531 bytes (replaced with small dummy file of size 0 bytes)

Skipped unused resource res/raw/oggmusic.ogg: 5335764 bytes (replaced with small dummy file of size 0 bytes)

I've done some research and there is a bug report on the Google Issue Tracker for this problem, however the poster says he/she used the information contained in the above link to make sure the required resources were not removed and the issue has been marked as 'intended behaviour' (which I find a little odd as I wouldn't have thought it would be intended behaviour for required resources to be removed).

Anyway, I've tried to do as mentioned in the docs and it doesn't seem to work, what am I doing wrong here? I've created an xml file called 'keep.xml' and placed it into my raw folder alongside the resources to keep.

This is the XML:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
       tools:keep="@raw/*.mp3, @raw/*.ogg"/>

This issue wasn't evident in Eclipse, but has appeared since migrating to Android Studio.

EDIT

I did a bit more testing and I can confirm that whatever I specify in the XML file is being completely ignored. If I use "discard" for example instead of, or in place of 'keep', the resources stated in 'discard' appear in the generated APK file, so I must be doing something wrong or missing a step out somewhere.


Solution

  • I just experienced this issue and have found out what I was doing wrong.

    Do not specify file extensions when referring to resources.

    What I did at first (this will not work):

    <?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:tools="http://schemas.android.com/tools"
        tools:keep="@raw/vid.mp4"
        />
    

    Solution, drop the file extension:

    <?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:tools="http://schemas.android.com/tools"
        tools:keep="@raw/vid"
        />
    

    You can verify this by inspecting the resources.txt file that you can find at ./app/build/outputs/mapping/<buildType>/resources.txt https://developer.android.com/studio/build/shrink-code