Search code examples
androidapk-expansion-files

Access Expansion File Globally


I need to access a lot of images from the expansion file throughout a lot of activities.

Doing the:

expansionFile = APKExpansionSupport.getAPKExpansionZipFile(context, 8, -1);
fileStream = expansionFile.getInputStream("drawables/drawable-hdpi/" + image);
Drawable drawable = Drawable.createFromStream(fileStream, null);

for every activity is very slow, in some activities I need to load 4 ou more images at the same time.

So what do you think if I create a new class that abstracts this code in every activity?


Solution

  • So I created a class ExpansionFileRetriever, that retrieves the expansion file:

    public class ExpansionFileRetriever{

    private static ExpansionFileRetriever instance;
    
    public static ExpansionFileRetriever get() {
       if(instance == null) instance = getSync();
       return instance;
    }
    
    private static synchronized ExpansionFileRetriever getSync() {
       if(instance == null) instance = new ExpansionFileRetriever();
       return instance;
    }
    
    public ExpansionFileRetriever(){
       // here you can directly access the Application context calling
       Context c = App.get();
       try {
            expansionFile = APKExpansionSupport.getAPKExpansionZipFile(c, 20, -1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    ZipResourceFile expansionFile;
    
    public Drawable getDrawable(String path, String resource) {
        InputStream fileStream = null;
        String file = path + resource;
        try {
            fileStream = expansionFile.getInputStream(file);
            Drawable drawable = Drawable.createFromStream(fileStream, null);
            return drawable;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }   
    }
    

    }

    and whenever I need to access files for the expansion file

    I just use

    ExpansionFileRetriever expFile = ExpansionFileRetriever.get();
    

    and to get, say a Drawable all I do is:

    expFile.getDrawable(path, name)