Implementing CWAC provider - The right way.
Many a times an app may want to share a resource file from its asset or resource library to another app . For example sending a audio clip from the app with whats-app/fb or any other easy-share option.
The pre-existing option developed by android is using a content-provider sub function called file provider.
Its an easy but inefficient way to serve files from internal resources to external apps. Moreover it doesn't support serving files from res directory thus limiting file access only to Assets folder.
The only two other option remain are :
Copying the file first to apps internal dir > Sharing the file from there by supplying the appropriate uri > Hope user doesn't gets annoyed to see the app requesting permission to store files and accepts the permission > Delete the file from internal app dir.
Use CWAC Provider by commonsguy.
CWAC-Provider is a seriously awesome and efficient library to build custom uri(s) to serve files from any internal directory be it res/raw/assets , you name it.
This is literally the first line of description of this lib -->
CWAC-Provider: Helping to Make Content Providers Sane
The only problem is this lib is not as popular as commonguy's other libs and the documentation is too short but precise. The lack of examples for serving the file from res/raw folder instead of assets is also the reason this library threw me off at first when I was building the joker-soundboard app. After a bit of careful library review I finally figured out how to use this for res folders.
Here's the example and usage details of the same -->
/res/xml/resources.xml file -->
<paths> <raw-resource name="file0_name" path="file0_name"></raw-resource> <raw-resource name="file1_name" path="file1_name"></raw-resource> </paths>
/res/values/arrays.xml file -->
<string-array name="provider_paths"> <item>file0_name.mp3</item> <item>file1_name.mp3</item> </string-array>
/src/main/AndroidManifest.xml // Manifest file
</activity> <provider android:name="com.commonsware.cwac.provider.StreamProvider" android:authorities="company.package.name" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="com.commonsware.cwac.provider.STREAM_PROVIDER_PATHS" android:resource="@xml/resources"/><meta-data android:name="com.commonsware.cwac.provider.USE_LEGACY_CURSOR_WRAPPER" android:value="true"/><meta-data android:name="com.commonsware.cwac.provider.USE_URI_FOR_DATA_COLUMN" android:value="true"/></provider> </application>