Search in sources :

Example 11 with AssetManager

use of android.content.res.AssetManager in project MagicCamera by wuhaoyu1990.

the class OpenGlUtils method getImageFromAssetsFile.

private static Bitmap getImageFromAssetsFile(Context context, String fileName) {
    Bitmap image = null;
    AssetManager am = context.getResources().getAssets();
    try {
        InputStream is = am.open(fileName);
        image = BitmapFactory.decodeStream(is);
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}
Also used : Bitmap(android.graphics.Bitmap) AssetManager(android.content.res.AssetManager) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 12 with AssetManager

use of android.content.res.AssetManager in project XobotOS by xamarin.

the class ActivityThread method getTopLevelResources.

/**
     * Creates the top level Resources for applications with the given compatibility info.
     *
     * @param resDir the resource directory.
     * @param compInfo the compability info. It will use the default compatibility info when it's
     * null.
     */
Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
    ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
    Resources r;
    synchronized (mPackages) {
        // Resources is app scale dependent.
        if (false) {
            Slog.w(TAG, "getTopLevelResources: " + resDir + " / " + compInfo.applicationScale);
        }
        WeakReference<Resources> wr = mActiveResources.get(key);
        r = wr != null ? wr.get() : null;
        //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
        if (r != null && r.getAssets().isUpToDate()) {
            if (false) {
                Slog.w(TAG, "Returning cached resources " + r + " " + resDir + ": appScale=" + r.getCompatibilityInfo().applicationScale);
            }
            return r;
        }
    }
    //if (r != null) {
    //    Slog.w(TAG, "Throwing away out-of-date resources!!!! "
    //            + r + " " + resDir);
    //}
    AssetManager assets = new AssetManager();
    if (assets.addAssetPath(resDir) == 0) {
        return null;
    }
    //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
    DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
    r = new Resources(assets, metrics, getConfiguration(), compInfo);
    if (false) {
        Slog.i(TAG, "Created app resources " + resDir + " " + r + ": " + r.getConfiguration() + " appScale=" + r.getCompatibilityInfo().applicationScale);
    }
    synchronized (mPackages) {
        WeakReference<Resources> wr = mActiveResources.get(key);
        Resources existing = wr != null ? wr.get() : null;
        if (existing != null && existing.getAssets().isUpToDate()) {
            // Someone else already created the resources while we were
            // unlocked; go ahead and use theirs.
            r.getAssets().close();
            return existing;
        }
        // XXX need to remove entries when weak references go away
        mActiveResources.put(key, new WeakReference<Resources>(r));
        return r;
    }
}
Also used : AssetManager(android.content.res.AssetManager) Resources(android.content.res.Resources) DisplayMetrics(android.util.DisplayMetrics)

Example 13 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 14 with AssetManager

use of android.content.res.AssetManager in project weiciyuan by qii.

the class GlobalContext method getEmotionsTask.

private LinkedHashMap<String, Bitmap> getEmotionsTask(Map<String, String> emotionMap) {
    List<String> index = new ArrayList<String>();
    index.addAll(emotionMap.keySet());
    LinkedHashMap<String, Bitmap> bitmapMap = new LinkedHashMap<String, Bitmap>();
    for (String str : index) {
        String name = emotionMap.get(str);
        AssetManager assetManager = GlobalContext.getInstance().getAssets();
        InputStream inputStream;
        try {
            inputStream = assetManager.open(name);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, Utility.dip2px(getResources().getInteger(R.integer.emotion_size)), Utility.dip2px(getResources().getInteger(R.integer.emotion_size)), true);
                if (bitmap != scaledBitmap) {
                    bitmap.recycle();
                    bitmap = scaledBitmap;
                }
                bitmapMap.put(str, bitmap);
            }
        } catch (IOException ignored) {
        }
    }
    return bitmapMap;
}
Also used : Bitmap(android.graphics.Bitmap) AssetManager(android.content.res.AssetManager) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 15 with AssetManager

use of android.content.res.AssetManager in project mobile-android by photo.

the class TroveboxApiTest method createTestFileForUpload.

public File createTestFileForUpload() throws Exception, IOException {
    AssetManager assetMgr = getTestContext().getAssets();
    InputStream imageStream = assetMgr.open("android.jpg");
    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/com.trovebox.android");
    if (!dir.exists()) {
        assertTrue(dir.mkdirs());
    }
    File file = new File(dir, "test-android.jpg");
    FileUtils.writeToFile(imageStream, file);
    return file;
}
Also used : AssetManager(android.content.res.AssetManager) InputStream(java.io.InputStream) File(java.io.File)

Aggregations

AssetManager (android.content.res.AssetManager)201 IOException (java.io.IOException)75 InputStream (java.io.InputStream)60 Resources (android.content.res.Resources)48 XmlResourceParser (android.content.res.XmlResourceParser)28 File (java.io.File)28 DisplayMetrics (android.util.DisplayMetrics)25 Configuration (android.content.res.Configuration)16 Bitmap (android.graphics.Bitmap)13 BufferedReader (java.io.BufferedReader)13 FileOutputStream (java.io.FileOutputStream)13 InputStreamReader (java.io.InputStreamReader)12 FileInputStream (java.io.FileInputStream)10 FileNotFoundException (java.io.FileNotFoundException)10 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)10 Intent (android.content.Intent)8 AndroidRuntimeException (android.util.AndroidRuntimeException)8 OutputStream (java.io.OutputStream)8 Method (java.lang.reflect.Method)8 AttributeSet (android.util.AttributeSet)7