Search in sources :

Example 51 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 52 with WeakReference

use of java.lang.ref.WeakReference in project android_frameworks_base by ParanoidAndroid.

the class SparseWeakArray method append.

/**
     * Puts a key/value pair into the array, optimizing for the case where
     * the key is greater than all existing keys in the array.
     */
public void append(int key, E value) {
    if (mSize != 0 && key <= mKeys[mSize - 1]) {
        put(key, value);
        return;
    }
    if (mSize >= mKeys.length && (mGarbage || hasReclaimedRefs())) {
        gc();
    }
    int pos = mSize;
    if (pos >= mKeys.length) {
        int n = ArrayUtils.idealIntArraySize(pos + 1);
        int[] nkeys = new int[n];
        WeakReference<?>[] nvalues = new WeakReference[n];
        // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
        System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
        System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
        mKeys = nkeys;
        mValues = nvalues;
    }
    mKeys[pos] = key;
    mValues[pos] = new WeakReference(value);
    mSize = pos + 1;
}
Also used : WeakReference(java.lang.ref.WeakReference)

Example 53 with WeakReference

use of java.lang.ref.WeakReference in project LogisticsPipes by RS485.

the class ChestGuiOpened method processPacket.

@Override
public void processPacket(EntityPlayer player) {
    List<WeakReference<ModuleQuickSort>> list = LogisticsEventListener.chestQuickSortConnection.get(player);
    if (list == null || list.isEmpty()) {
        return;
    }
    MainProxy.sendPacketToPlayer(PacketHandler.getPacket(EnableQuickSortMarker.class), player);
    for (WeakReference<ModuleQuickSort> sorter : list) {
        ModuleQuickSort module = sorter.get();
        if (module == null) {
            continue;
        }
        module.addWatchingPlayer(player);
    }
}
Also used : WeakReference(java.lang.ref.WeakReference) ModuleQuickSort(logisticspipes.modules.ModuleQuickSort)

Example 54 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 55 with WeakReference

use of java.lang.ref.WeakReference in project android_frameworks_base by ParanoidAndroid.

the class ActivityThread method applyConfigurationToResourcesLocked.

final int applyConfigurationToResourcesLocked(Configuration config, CompatibilityInfo compat) {
    if (mResConfiguration == null) {
        mResConfiguration = new Configuration();
    }
    if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
        if (DEBUG_CONFIGURATION)
            Slog.v(TAG, "Skipping new config: curSeq=" + mResConfiguration.seq + ", newSeq=" + config.seq);
        return 0;
    }
    int changes = mResConfiguration.updateFrom(config);
    flushDisplayMetricsLocked();
    DisplayMetrics defaultDisplayMetrics = getDisplayMetricsLocked(Display.DEFAULT_DISPLAY, null);
    if (compat != null && (mResCompatibilityInfo == null || !mResCompatibilityInfo.equals(compat))) {
        mResCompatibilityInfo = compat;
        changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT | ActivityInfo.CONFIG_SCREEN_SIZE | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
    }
    // set it for java, this also affects newly created Resources
    if (config.locale != null) {
        Locale.setDefault(config.locale);
    }
    Resources.updateSystemConfiguration(config, defaultDisplayMetrics, compat);
    ApplicationPackageManager.configurationChanged();
    //Slog.i(TAG, "Configuration changed in " + currentPackageName());
    Configuration tmpConfig = null;
    Iterator<Map.Entry<ResourcesKey, WeakReference<Resources>>> it = mActiveResources.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<ResourcesKey, WeakReference<Resources>> entry = it.next();
        Resources r = entry.getValue().get();
        if (r != null) {
            if (DEBUG_CONFIGURATION)
                Slog.v(TAG, "Changing resources " + r + " config to: " + config);
            int displayId = entry.getKey().mDisplayId;
            boolean isDefaultDisplay = (displayId == Display.DEFAULT_DISPLAY);
            DisplayMetrics dm = defaultDisplayMetrics;
            Configuration overrideConfig = entry.getKey().mOverrideConfiguration;
            boolean themeChanged = (changes & ActivityInfo.CONFIG_THEME_RESOURCE) != 0;
            if (themeChanged) {
                AssetManager am = r.getAssets();
                if (am.hasThemeSupport()) {
                    detachThemeAssets(am);
                    if (!TextUtils.isEmpty(config.customTheme.getThemePackageName())) {
                        attachThemeAssets(am, config.customTheme);
                    }
                }
            }
            if (!isDefaultDisplay || overrideConfig != null) {
                if (tmpConfig == null) {
                    tmpConfig = new Configuration();
                }
                tmpConfig.setTo(config);
                if (!isDefaultDisplay) {
                    dm = getDisplayMetricsLocked(displayId, null);
                    applyNonDefaultDisplayMetricsToConfigurationLocked(dm, tmpConfig);
                }
                if (overrideConfig != null) {
                    tmpConfig.updateFrom(overrideConfig);
                }
                r.updateConfiguration(tmpConfig, dm, compat);
            } else {
                r.updateConfiguration(config, dm, compat);
            }
            if (themeChanged) {
                r.updateStringCache();
            }
        //Slog.i(TAG, "Updated app resources " + v.getKey()
        //        + " " + r + ": " + r.getConfiguration());
        } else {
            //Slog.i(TAG, "Removing old resources " + v.getKey());
            it.remove();
        }
    }
    return changes;
}
Also used : AssetManager(android.content.res.AssetManager) Configuration(android.content.res.Configuration) WeakReference(java.lang.ref.WeakReference) Resources(android.content.res.Resources) DisplayMetrics(android.util.DisplayMetrics) PackageRedirectionMap(android.content.res.PackageRedirectionMap) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

WeakReference (java.lang.ref.WeakReference)291 ArrayList (java.util.ArrayList)32 HashMap (java.util.HashMap)24 Map (java.util.Map)24 Field (java.lang.reflect.Field)19 Activity (android.app.Activity)17 Iterator (java.util.Iterator)17 IOException (java.io.IOException)16 Method (java.lang.reflect.Method)15 File (java.io.File)14 URLClassLoader (java.net.URLClassLoader)14 Test (org.junit.Test)13 Reference (java.lang.ref.Reference)12 ReferenceQueue (java.lang.ref.ReferenceQueue)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