How to reference Android 'assets' across p

2019-03-16 09:28发布

问题:

I have an Android App that is published in a 'free' and 'pro' version. I have set up my project with a base 'library' project that is referenced from both versions, such that my package set looks like this:

  • com.example.myapp
  • com.example.myapp.free
  • com.example.myapp.pro

One of the Activity classes in my base 'library' project loads a help file into a WebView: WebView.loadUrl("file:///android_asset/help.html"). This class is extended in both the 'free' and 'pro' versions (for reasons outside the scope of this question), but I'd like both versions to reference the same HTML file (i.e. the one in the parent package). Under my current set up, however, the HTML file needs to be duplicated in the 'assets' folder under the 'com.example.myapp.free' and 'com.example.myapp.pro' packages for the "file:///android_asset/" URI to work.

Is there a way to specify the "file:///android_asset/" URI such that it accesses the 'assets' directory in the parent package?

A partial solution I found involves reading the HTML file from the 'raw' directory and then pushing the resulting string to my WebView object, but this would be messy to do for anything more than a text-only HTML page (e.g. one with images, like my one).

Cheers.

回答1:

Since Andrew White didn't explain how to do what he recommends against, I'll show you:

Context otherContext = context.createPackageContext("other.package.name", 0);
AssetManager am = otherContext.getAssets();

That doesn't seem so bad. And I've verified that there's no need for the two packages to share a user ID.



回答2:

As a developer that has both pro and free versions out there I can say from experience, don't try to share assets across applications. Even if you get it to work, you'll end up with more hassle than it's worth.

If you absolutely must do this, each app must share the same system user and you must create a context in one app that mimics the other. These aren't hard to do but and can be a maintenance nightmare.