Search code examples
androidhtmlpathandroid-webviewapk-expansion-files

Load images using html <img> tag from Android expansion file


I am trying to load my HTML files from Android expansion file(.obb) using WebView like

    String prompt = "";
    WebView webview = (WebView) rootView.findViewById(R.id.webview);

    try {
        InputStream html = getAssetFileDescriptor("www/" + mResult.getTitle() + ".html")
                .createInputStream();
        byte[] b = new byte[html.available()];
        html.read(b);
        prompt = new String(b);
        html.close();

    } catch (IOException e) {
        Log.e("Webview", "Couldn't open webpage");
    }

    webview.loadData(prompt, "text/html", "utf-8");

*getAssetFileDescriptor returns InputStream read by ZipResourceFile function(Zip file library)

It loads HTML into Webview successfully but all the images inside the HTML are not appearing.

I guess It's because it cannot access to image files through img tags.

for example, my html files have img tags like

<img src="./image1.jpg" />

Relative path seems not working because html and image files are zipped into obb file.

How can I fix it?


Solution

  • You can mount the OBB file using StorageManager:

    StorageManager storageManager = (StorageManager)app.getSystemService(Context.STORAGE_SERVICE);
    boolean queued = storageManager.mountObb(<path>, null, new OnObbStateChangeListsner() {...});
    

    Then, you can use this path to construct a path to your files: the returned path is the root to your OBB:

    storageManager.getMountedObbPath(...) + "/image1.jpg";
    

    an use that path to load your image

    <img src="your_path" />