summaryrefslogtreecommitdiffstats
path: root/base/android/java/src/org/chromium/base/ApkAssets.java
blob: e00be9924b4e0da679581549f83feab7663063c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.util.Log;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

import java.io.IOException;

/**
 * A utility class to retrieve references to uncompressed assets insides the apk. A reference is
 * defined as tuple (file descriptor, offset, size) enabling direct mapping without deflation.
 * This can be used even within the renderer process, since it just dup's the apk's fd.
 */
@JNINamespace("base::android")
public class ApkAssets {
    private static final String LOGTAG = "ApkAssets";

    @CalledByNative
    public static long[] open(Context context, String fileName) {
        AssetFileDescriptor afd = null;
        try {
            AssetManager manager = context.getAssets();
            afd = manager.openNonAssetFd(fileName);
            return new long[] { afd.getParcelFileDescriptor().detachFd(),
                                afd.getStartOffset(),
                                afd.getLength() };
        } catch (IOException e) {
            Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e);
            return new long[] {-1, -1, -1};
        } finally {
            try {
                if (afd != null) {
                    afd.close();
                }
            } catch (IOException e2) {
                Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2);
            }
        }
    }
}