Search in sources :

Example 36 with AssetManager

use of android.content.res.AssetManager in project muzei by romannurik.

the class DownloadArtworkTask method openUri.

private InputStream openUri(Context context, Uri uri) throws IOException {
    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }
    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new IOException("Uri had no scheme");
    }
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (SecurityException e) {
            throw new FileNotFoundException("No access to " + uri + ": " + e.toString());
        }
    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            in = assetManager.open(assetPath.toString());
        } else {
            in = new FileInputStream(new File(uri.getPath()));
        }
    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = OkHttpClientFactory.getNewOkHttpsSafeClient();
        Request request;
        request = new Request.Builder().url(new URL(uri.toString())).build();
        Response response = client.newCall(request).execute();
        int responseCode = response.code();
        if (!(responseCode >= 200 && responseCode < 300)) {
            throw new IOException("HTTP error response " + responseCode);
        }
        in = response.body().byteStream();
    }
    if (in == null) {
        throw new FileNotFoundException("Null input stream for URI: " + uri);
    }
    return in;
}
Also used : AssetManager(android.content.res.AssetManager) OkHttpClient(okhttp3.OkHttpClient) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) Request(okhttp3.Request) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) URL(java.net.URL) Response(okhttp3.Response) List(java.util.List) File(java.io.File)

Example 37 with AssetManager

use of android.content.res.AssetManager in project platform_frameworks_base by android.

the class Font method createFromAsset.

/**
     * @deprecated in API 16
     */
public static Font createFromAsset(RenderScript rs, Resources res, String path, float pointSize) {
    rs.validate();
    AssetManager mgr = res.getAssets();
    int dpi = res.getDisplayMetrics().densityDpi;
    long fontId = rs.nFontCreateFromAsset(mgr, path, pointSize, dpi);
    if (fontId == 0) {
        throw new RSRuntimeException("Unable to create font from asset " + path);
    }
    Font rsFont = new Font(fontId, rs);
    return rsFont;
}
Also used : AssetManager(android.content.res.AssetManager)

Example 38 with AssetManager

use of android.content.res.AssetManager in project platform_frameworks_base by android.

the class PackageParser method parseApkLite.

/**
     * Utility method that retrieves lightweight details about a single APK
     * file, including package name, split name, and install location.
     *
     * @param apkFile path to a single APK
     * @param flags optional parse flags, such as
     *            {@link #PARSE_COLLECT_CERTIFICATES}
     */
public static ApkLite parseApkLite(File apkFile, int flags) throws PackageParserException {
    final String apkPath = apkFile.getAbsolutePath();
    AssetManager assets = null;
    XmlResourceParser parser = null;
    try {
        assets = new AssetManager();
        assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Build.VERSION.RESOURCES_SDK_INT);
        int cookie = assets.addAssetPath(apkPath);
        if (cookie == 0) {
            throw new PackageParserException(INSTALL_PARSE_FAILED_NOT_APK, "Failed to parse " + apkPath);
        }
        final DisplayMetrics metrics = new DisplayMetrics();
        metrics.setToDefaults();
        final Resources res = new Resources(assets, metrics, null);
        parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);
        final Signature[] signatures;
        final Certificate[][] certificates;
        if ((flags & PARSE_COLLECT_CERTIFICATES) != 0) {
            // TODO: factor signature related items out of Package object
            final Package tempPkg = new Package(null);
            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
            try {
                collectCertificates(tempPkg, apkFile, 0);
            } finally {
                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
            }
            signatures = tempPkg.mSignatures;
            certificates = tempPkg.mCertificates;
        } else {
            signatures = null;
            certificates = null;
        }
        final AttributeSet attrs = parser;
        return parseApkLite(apkPath, res, parser, attrs, flags, signatures, certificates);
    } catch (XmlPullParserException | IOException | RuntimeException e) {
        throw new PackageParserException(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION, "Failed to parse " + apkPath, e);
    } finally {
        IoUtils.closeQuietly(parser);
        IoUtils.closeQuietly(assets);
    }
}
Also used : AssetManager(android.content.res.AssetManager) XmlResourceParser(android.content.res.XmlResourceParser) IOException(java.io.IOException) DisplayMetrics(android.util.DisplayMetrics) AttributeSet(android.util.AttributeSet) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) Resources(android.content.res.Resources)

Example 39 with AssetManager

use of android.content.res.AssetManager in project freeline by alibaba.

the class MonkeyPatcher method monkeyPatchExistingResources.

public static void monkeyPatchExistingResources(Context context, String externalResourceFile, Collection<Activity> activities) {
    if (externalResourceFile == null) {
        return;
    }
    /*
        (Note: the resource directory is *also* inserted into the loadedApk in
        monkeyPatchApplication)
        The code seems to perform this:
        File externalResourceFile = <path to resources.ap_ or extracted directory>
        AssetManager newAssetManager = new AssetManager();
        newAssetManager.addAssetPath(externalResourceFile)
        // Kitkat needs this method call, Lollipop doesn't. However, it doesn't seem to cause any harm
        // in L, so we do it unconditionally.
        newAssetManager.ensureStringBlocks();
        // Find the singleton instance of ResourcesManager
        ResourcesManager resourcesManager = ResourcesManager.getInstance();
        // Iterate over all known Resources objects
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            for (WeakReference<Resources> wr : resourcesManager.mActiveResources.values()) {
                Resources resources = wr.get();
                // Set the AssetManager of the Resources instance to our brand new one
                resources.mAssets = newAssetManager;
                resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
            }
        }
        // Also, for each context, call getTheme() to get the current theme; null out its
        // mTheme field, then invoke initializeTheme() to force it to be recreated (with the
        // new asset manager!)
        */
    try {
        // Create a new AssetManager instance and point it to the resources installed under
        // /sdcard
        AssetManager newAssetManager = AssetManager.class.getConstructor().newInstance();
        Method mAddAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
        mAddAssetPath.setAccessible(true);
        if (((Integer) mAddAssetPath.invoke(newAssetManager, externalResourceFile)) == 0) {
            throw new IllegalStateException("Could not create new AssetManager");
        }
        // Kitkat needs this method call, Lollipop doesn't. However, it doesn't seem to cause any harm
        // in L, so we do it unconditionally.
        Method mEnsureStringBlocks = AssetManager.class.getDeclaredMethod("ensureStringBlocks");
        mEnsureStringBlocks.setAccessible(true);
        mEnsureStringBlocks.invoke(newAssetManager);
        if (activities != null) {
            for (Activity activity : activities) {
                Resources resources = activity.getResources();
                try {
                    Field mAssets = Resources.class.getDeclaredField("mAssets");
                    mAssets.setAccessible(true);
                    mAssets.set(resources, newAssetManager);
                } catch (Throwable ignore) {
                    Field mResourcesImpl = Resources.class.getDeclaredField("mResourcesImpl");
                    mResourcesImpl.setAccessible(true);
                    Object resourceImpl = mResourcesImpl.get(resources);
                    Field implAssets = resourceImpl.getClass().getDeclaredField("mAssets");
                    implAssets.setAccessible(true);
                    implAssets.set(resourceImpl, newAssetManager);
                }
                Resources.Theme theme = activity.getTheme();
                try {
                    try {
                        Field ma = Resources.Theme.class.getDeclaredField("mAssets");
                        ma.setAccessible(true);
                        ma.set(theme, newAssetManager);
                    } catch (NoSuchFieldException ignore) {
                        Field themeField = Resources.Theme.class.getDeclaredField("mThemeImpl");
                        themeField.setAccessible(true);
                        Object impl = themeField.get(theme);
                        Field ma = impl.getClass().getDeclaredField("mAssets");
                        ma.setAccessible(true);
                        ma.set(impl, newAssetManager);
                    }
                    Field mt = ContextThemeWrapper.class.getDeclaredField("mTheme");
                    mt.setAccessible(true);
                    mt.set(activity, null);
                    Method mtm = ContextThemeWrapper.class.getDeclaredMethod("initializeTheme");
                    mtm.setAccessible(true);
                    mtm.invoke(activity);
                    if (SDK_INT < N) {
                        Method mCreateTheme = AssetManager.class.getDeclaredMethod("createTheme");
                        mCreateTheme.setAccessible(true);
                        Object internalTheme = mCreateTheme.invoke(newAssetManager);
                        Field mTheme = Resources.Theme.class.getDeclaredField("mTheme");
                        mTheme.setAccessible(true);
                        mTheme.set(theme, internalTheme);
                    }
                } catch (Throwable e) {
                    Log.e(LOG_TAG, "Failed to update existing theme for activity " + activity, e);
                }
                pruneResourceCaches(resources);
            }
        }
        // Iterate over all known Resources objects
        Collection<WeakReference<Resources>> references;
        if (SDK_INT >= KITKAT) {
            // Find the singleton instance of ResourcesManager
            Class<?> resourcesManagerClass = Class.forName("android.app.ResourcesManager");
            Method mGetInstance = resourcesManagerClass.getDeclaredMethod("getInstance");
            mGetInstance.setAccessible(true);
            Object resourcesManager = mGetInstance.invoke(null);
            try {
                Field fMActiveResources = resourcesManagerClass.getDeclaredField("mActiveResources");
                fMActiveResources.setAccessible(true);
                @SuppressWarnings("unchecked") ArrayMap<?, WeakReference<Resources>> arrayMap = (ArrayMap<?, WeakReference<Resources>>) fMActiveResources.get(resourcesManager);
                references = arrayMap.values();
            } catch (NoSuchFieldException ignore) {
                Field mResourceReferences = resourcesManagerClass.getDeclaredField("mResourceReferences");
                mResourceReferences.setAccessible(true);
                //noinspection unchecked
                references = (Collection<WeakReference<Resources>>) mResourceReferences.get(resourcesManager);
            }
        } else {
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Field fMActiveResources = activityThread.getDeclaredField("mActiveResources");
            fMActiveResources.setAccessible(true);
            Object thread = getActivityThread(context, activityThread);
            @SuppressWarnings("unchecked") HashMap<?, WeakReference<Resources>> map = (HashMap<?, WeakReference<Resources>>) fMActiveResources.get(thread);
            references = map.values();
        }
        for (WeakReference<Resources> wr : references) {
            Resources resources = wr.get();
            if (resources != null) {
                // Set the AssetManager of the Resources instance to our brand new one
                try {
                    Field mAssets = Resources.class.getDeclaredField("mAssets");
                    mAssets.setAccessible(true);
                    mAssets.set(resources, newAssetManager);
                } catch (Throwable ignore) {
                    Field mResourcesImpl = Resources.class.getDeclaredField("mResourcesImpl");
                    mResourcesImpl.setAccessible(true);
                    Object resourceImpl = mResourcesImpl.get(resources);
                    Field implAssets = resourceImpl.getClass().getDeclaredField("mAssets");
                    implAssets.setAccessible(true);
                    implAssets.set(resourceImpl, newAssetManager);
                }
                resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
            }
        }
    } catch (Throwable e) {
        throw new IllegalStateException(e);
    }
}
Also used : AssetManager(android.content.res.AssetManager) HashMap(java.util.HashMap) Activity(android.app.Activity) ArrayMap(android.util.ArrayMap) Method(java.lang.reflect.Method) Field(java.lang.reflect.Field) WeakReference(java.lang.ref.WeakReference) Collection(java.util.Collection) Resources(android.content.res.Resources)

Example 40 with AssetManager

use of android.content.res.AssetManager in project Lazy by l123456789jy.

the class MediaPlayerUtiles method playAudio.

/**
     * 播放音频
     */
public static void playAudio(Context mContext, String fileName) {
    try {
        //如果正在播放就停止
        stopAudio();
        AssetManager assetManager = mContext.getAssets();
        AssetFileDescriptor afd = assetManager.openFd(fileName);
        MediaPlayer mediaPlayer = getMediaPlayer();
        mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        //循环播放
        mediaPlayer.setLooping(false);
        mediaPlayer.prepare();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });
    } catch (Exception e) {
        Log.e("播放音频失败", "");
    }
}
Also used : AssetManager(android.content.res.AssetManager) AssetFileDescriptor(android.content.res.AssetFileDescriptor) MediaPlayer(android.media.MediaPlayer)

Aggregations

AssetManager (android.content.res.AssetManager)196 IOException (java.io.IOException)70 InputStream (java.io.InputStream)58 Resources (android.content.res.Resources)47 XmlResourceParser (android.content.res.XmlResourceParser)28 File (java.io.File)28 DisplayMetrics (android.util.DisplayMetrics)24 Configuration (android.content.res.Configuration)15 BufferedReader (java.io.BufferedReader)13 FileOutputStream (java.io.FileOutputStream)13 Bitmap (android.graphics.Bitmap)12 InputStreamReader (java.io.InputStreamReader)12 FileInputStream (java.io.FileInputStream)10 FileNotFoundException (java.io.FileNotFoundException)10 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)10 AndroidRuntimeException (android.util.AndroidRuntimeException)8 OutputStream (java.io.OutputStream)8 Method (java.lang.reflect.Method)8 Intent (android.content.Intent)7 AttributeSet (android.util.AttributeSet)7