Search in sources :

Example 11 with WeakReference

use of java.lang.ref.WeakReference in project robotium by RobotiumTech.

the class ActivityUtils method getAllOpenedActivities.

/**
	 * Returns a {@code List} of all the opened/active activities.
	 * 
	 * @return a {@code List} of all the opened/active activities
	 */
public ArrayList<Activity> getAllOpenedActivities() {
    ArrayList<Activity> activities = new ArrayList<Activity>();
    Iterator<WeakReference<Activity>> activityStackIterator = activityStack.iterator();
    while (activityStackIterator.hasNext()) {
        Activity activity = activityStackIterator.next().get();
        if (activity != null)
            activities.add(activity);
    }
    return activities;
}
Also used : WeakReference(java.lang.ref.WeakReference) ArrayList(java.util.ArrayList) Activity(android.app.Activity)

Example 12 with WeakReference

use of java.lang.ref.WeakReference in project tinker by Tencent.

the class TinkerResourcePatcher method monkeyPatchExistingResources.

/**
     * @param context
     * @param externalResourceFile
     * @throws Throwable
     */
public static void monkeyPatchExistingResources(Context context, String externalResourceFile) throws Throwable {
    if (externalResourceFile == null) {
        return;
    }
    for (Field field : new Field[] { packagesFiled, resourcePackagesFiled }) {
        Object value = field.get(currentActivityThread);
        for (Map.Entry<String, WeakReference<?>> entry : ((Map<String, WeakReference<?>>) value).entrySet()) {
            Object loadedApk = entry.getValue().get();
            if (loadedApk == null) {
                continue;
            }
            if (externalResourceFile != null) {
                resDir.set(loadedApk, externalResourceFile);
            }
        }
    }
    // Create a new AssetManager instance and point it to the resources installed under
    if (((Integer) addAssetPathMethod.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.
    ensureStringBlocksMethod.invoke(newAssetManager);
    for (WeakReference<Resources> wr : references) {
        Resources resources = wr.get();
        //pre-N
        if (resources != null) {
            // Set the AssetManager of the Resources instance to our brand new one
            try {
                assetsFiled.set(resources, newAssetManager);
            } catch (Throwable ignore) {
                // N
                Object resourceImpl = resourcesImplFiled.get(resources);
                // for Huawei HwResourcesImpl
                Field implAssets = ShareReflectUtil.findField(resourceImpl, "mAssets");
                implAssets.setAccessible(true);
                implAssets.set(resourceImpl, newAssetManager);
            }
            clearPreloadTypedArrayIssue(resources);
            resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
        }
    }
    if (!checkResUpdate(context)) {
        throw new TinkerRuntimeException(ShareConstants.CHECK_RES_INSTALL_FAIL);
    }
}
Also used : Field(java.lang.reflect.Field) WeakReference(java.lang.ref.WeakReference) Resources(android.content.res.Resources) HashMap(java.util.HashMap) Map(java.util.Map) ArrayMap(android.util.ArrayMap)

Example 13 with WeakReference

use of java.lang.ref.WeakReference in project tinker by Tencent.

the class TinkerResourcePatcher method isResourceCanPatch.

//    private static Field        publicSourceDirField     = null;
//    private static boolean isMiuiSystem = false;
public static void isResourceCanPatch(Context context) throws Throwable {
    //   - Replace mResDir to point to the external resource file instead of the .apk. This is
    //     used as the asset path for new Resources objects.
    //   - Set Application#mLoadedApk to the found LoadedApk instance
    // Find the ActivityThread instance for the current thread
    Class<?> activityThread = Class.forName("android.app.ActivityThread");
    currentActivityThread = ShareReflectUtil.getActivityThread(context, activityThread);
    // API version 8 has PackageInfo, 10 has LoadedApk. 9, I don't know.
    Class<?> loadedApkClass;
    try {
        loadedApkClass = Class.forName("android.app.LoadedApk");
    } catch (ClassNotFoundException e) {
        loadedApkClass = Class.forName("android.app.ActivityThread$PackageInfo");
    }
    resDir = loadedApkClass.getDeclaredField("mResDir");
    resDir.setAccessible(true);
    packagesFiled = activityThread.getDeclaredField("mPackages");
    packagesFiled.setAccessible(true);
    resourcePackagesFiled = activityThread.getDeclaredField("mResourcePackages");
    resourcePackagesFiled.setAccessible(true);
    // Create a new AssetManager instance and point it to the resources
    AssetManager assets = context.getAssets();
    // Baidu os
    if (assets.getClass().getName().equals("android.content.res.BaiduAssetManager")) {
        Class baiduAssetManager = Class.forName("android.content.res.BaiduAssetManager");
        newAssetManager = (AssetManager) baiduAssetManager.getConstructor().newInstance();
    } else {
        newAssetManager = AssetManager.class.getConstructor().newInstance();
    }
    addAssetPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
    addAssetPathMethod.setAccessible(true);
    // Kitkat needs this method call, Lollipop doesn't. However, it doesn't seem to cause any harm
    // in L, so we do it unconditionally.
    ensureStringBlocksMethod = AssetManager.class.getDeclaredMethod("ensureStringBlocks");
    ensureStringBlocksMethod.setAccessible(true);
    // Iterate over all known Resources objects
    if (SDK_INT >= KITKAT) {
        //pre-N
        // 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);
            ArrayMap<?, WeakReference<Resources>> activeResources19 = (ArrayMap<?, WeakReference<Resources>>) fMActiveResources.get(resourcesManager);
            references = activeResources19.values();
        } catch (NoSuchFieldException ignore) {
            // N moved the resources to mResourceReferences
            Field mResourceReferences = resourcesManagerClass.getDeclaredField("mResourceReferences");
            mResourceReferences.setAccessible(true);
            //                resourceImpls = (ArrayMap<?, WeakReference<?>>) mResourceReferences.get("mResourceImpls");
            references = (Collection<WeakReference<Resources>>) mResourceReferences.get(resourcesManager);
        }
    } else {
        Field fMActiveResources = activityThread.getDeclaredField("mActiveResources");
        fMActiveResources.setAccessible(true);
        HashMap<?, WeakReference<Resources>> activeResources7 = (HashMap<?, WeakReference<Resources>>) fMActiveResources.get(currentActivityThread);
        references = activeResources7.values();
    }
    // check resource
    if (references == null) {
        throw new IllegalStateException("resource references is null");
    }
    try {
        assetsFiled = Resources.class.getDeclaredField("mAssets");
        assetsFiled.setAccessible(true);
    } catch (Throwable ignore) {
        // N moved the mAssets inside an mResourcesImpl field
        resourcesImplFiled = Resources.class.getDeclaredField("mResourcesImpl");
        resourcesImplFiled.setAccessible(true);
    }
//        final Resources resources = context.getResources();
//        isMiuiSystem = resources != null && MIUI_RESOURCE_CLASSNAME.equals(resources.getClass().getName());
//        try {
//            publicSourceDirField = ShareReflectUtil.findField(ApplicationInfo.class, "publicSourceDir");
//        } catch (NoSuchFieldException e) {
//            throw new IllegalStateException("cannot find 'mInstrumentation' field");
//        }
}
Also used : AssetManager(android.content.res.AssetManager) HashMap(java.util.HashMap) 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 WeakReference

use of java.lang.ref.WeakReference in project PneumaticCraft by MineMaarten.

the class VisNetHandler method calculateNearbyNodes.

private static void calculateNearbyNodes(World world, int x, int y, int z) {
    HashMap<WorldCoordinates, WeakReference<TileVisNode>> sourcelist = sources.get(world.provider.dimensionId);
    if (sourcelist == null) {
        sourcelist = new HashMap<WorldCoordinates, WeakReference<TileVisNode>>();
        return;
    }
    ArrayList<WeakReference<TileVisNode>> cn = new ArrayList<WeakReference<TileVisNode>>();
    WorldCoordinates drainer = new WorldCoordinates(x, y, z, world.provider.dimensionId);
    ArrayList<Object[]> nearby = new ArrayList<Object[]>();
    for (WeakReference<TileVisNode> root : sourcelist.values()) {
        if (!isNodeValid(root))
            continue;
        TileVisNode source = root.get();
        TileVisNode closest = null;
        float range = Float.MAX_VALUE;
        float r = inRange(world, drainer, source.getLocation(), source.getRange());
        if (r > 0) {
            range = r;
            closest = source;
        }
        ArrayList<WeakReference<TileVisNode>> children = new ArrayList<WeakReference<TileVisNode>>();
        children = getAllChildren(source, children);
        for (WeakReference<TileVisNode> child : children) {
            TileVisNode n = child.get();
            if (n != null && !n.equals(root)) {
                float r2 = inRange(n.getWorldObj(), n.getLocation(), drainer, n.getRange());
                if (r2 > 0 && r2 < range) {
                    range = r2;
                    closest = n;
                }
            }
        }
        if (closest != null) {
            cn.add(new WeakReference(closest));
        }
    }
    nearbyNodes.put(drainer, cn);
}
Also used : WeakReference(java.lang.ref.WeakReference) WorldCoordinates(thaumcraft.api.WorldCoordinates) ArrayList(java.util.ArrayList)

Example 15 with WeakReference

use of java.lang.ref.WeakReference in project PneumaticCraft by MineMaarten.

the class VisNetHandler method drainVis.

// NODE DRAINING
/**
	 * This method drains vis from a relay or source near the passed in
	 * location. The amount received can be less than the amount requested so
	 * take that into account.
	 * 
	 * @param world
	 * @param x the x position of the draining block or entity
	 * @param y the y position of the draining block or entity
	 * @param z the z position of the draining block or entity
	 * @param aspect what aspect to drain
	 * @param amount how much to drain
	 * @return how much was actually drained
	 */
public static int drainVis(World world, int x, int y, int z, Aspect aspect, int amount) {
    int drainedAmount = 0;
    WorldCoordinates drainer = new WorldCoordinates(x, y, z, world.provider.dimensionId);
    if (!nearbyNodes.containsKey(drainer)) {
        calculateNearbyNodes(world, x, y, z);
    }
    ArrayList<WeakReference<TileVisNode>> nodes = nearbyNodes.get(drainer);
    if (nodes != null && nodes.size() > 0)
        for (WeakReference<TileVisNode> noderef : nodes) {
            TileVisNode node = noderef.get();
            if (node == null)
                continue;
            int a = node.consumeVis(aspect, amount);
            drainedAmount += a;
            amount -= a;
            if (a > 0) {
                int color = Aspect.getPrimalAspects().indexOf(aspect);
                generateVisEffect(world.provider.dimensionId, x, y, z, node.xCoord, node.yCoord, node.zCoord, color);
            }
            if (amount <= 0) {
                break;
            }
        }
    return drainedAmount;
}
Also used : WeakReference(java.lang.ref.WeakReference) WorldCoordinates(thaumcraft.api.WorldCoordinates)

Aggregations

WeakReference (java.lang.ref.WeakReference)277 ArrayList (java.util.ArrayList)31 HashMap (java.util.HashMap)19 Map (java.util.Map)19 Field (java.lang.reflect.Field)18 Activity (android.app.Activity)17 Method (java.lang.reflect.Method)15 File (java.io.File)14 IOException (java.io.IOException)13 URLClassLoader (java.net.URLClassLoader)13 Test (org.junit.Test)13 Reference (java.lang.ref.Reference)12 ReferenceQueue (java.lang.ref.ReferenceQueue)12 Iterator (java.util.Iterator)12 Resources (android.content.res.Resources)10 Handler (android.os.Handler)10 AbstractModule (com.google.inject.AbstractModule)10 Injector (com.google.inject.Injector)10 ArrayMap (android.util.ArrayMap)9 URL (java.net.URL)8