Hello,
I'm trying to load/reference images from the app's assets folder from within a HTML page in a WebView. Unlike in most of the examples the HTML page itself is not located in the assets folder but is loaded from a server via http. The background of this question are some performance improvements which should reduce the loading time (and the amount of transferred data) by loading static images directly from the device. I'm not sure if Android has some restrictions here because there's a certain possibility to exploit the app by allowing access to the local file storage from a remotely loaded webpage.
I first tried to load images using <img src="file:///android_asset/myimage.png">
but this failed (for obvious reasons). My next attempt was to use a ContentProvider
class and reference images using <img src="content://com.myapp.assetcontentprovider/myimage.png">
. This ContentProvider is implemented as follows:
public class AssetContentProvider extends ContentProvider
{
private static final String URI_PREFIX = "content://com.myapp.assetcontentprovider";
public static String constructUri(String url) {
Uri uri = Uri.parse(url);
return uri.isAbsolute() ? url : URI_PREFIX + url;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Log.d("AssetContentProvider", uri.getPath());
try {
return getContext().getAssets().openFd(uri.getPath().substring(1)).getParcelFileDescriptor();
} catch (IOException e) {
Log.d("AssetContentProvider", "IOException for " + uri.getPath());
throw new FileNotFoundException();
}
}
// more methods irrelevant for this post
}
When loading the HTML page I can see in the debug log that openFile()
is actually triggered from the WebView and it returns a valid ParcelFileDescriptor
object but still the image is not displayed. There are no error messages shown in the log which would tell me that WebView refused to load/display the image. Any ideas if and how this could work?