Java Code Examples for com.bumptech.glide.util.Util#assertMainThread()

The following examples show how to use com.bumptech.glide.util.Util#assertMainThread() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericRequest.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Cancels the current load if it is in progress, clears any resources held onto by the request and replaces
 * the loaded resource if the load completed with the placeholder.
 *
 * <p>
 *     Cleared requests can be restarted with a subsequent call to {@link #begin()}
 * </p>
 *
 * @see #cancel()
 */
@Override
public void clear() {
    Util.assertMainThread();
    if (status == Status.CLEARED) {
        return;
    }
    cancel();
    // Resource must be released before canNotifyStatusChanged is called.
    if (resource != null) {
        releaseResource(resource);
    }
    if (canNotifyStatusChanged()) {
        target.onLoadCleared(getPlaceholderDrawable());
    }
    // Must be after cancel().
    status = Status.CLEARED;
}
 
Example 2
Source File: GenericRequestBuilder.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the {@link ImageView} the resource will be loaded into, cancels any existing loads into the view, and frees
 * any resources Glide may have previously loaded into the view so they may be reused.
 *
 * @see Glide#clear(android.view.View)
 *
 * @param view The view to cancel previous loads for and load the new resource into.
 * @return The {@link Target} used to wrap the given {@link ImageView}.
 */
public Target<TranscodeType> into(ImageView view) {
    Util.assertMainThread();
    if (view == null) {
        throw new IllegalArgumentException("You must pass in a non null View");
    }

    if (!isTransformationSet && view.getScaleType() != null) {
        switch (view.getScaleType()) {
            case CENTER_CROP:
                applyCenterCrop();
                break;
            case FIT_CENTER:
            case FIT_START:
            case FIT_END:
                applyFitCenter();
                break;
            //$CASES-OMITTED$
            default:
                // Do nothing.
        }
    }

    return into(glide.buildImageViewTarget(view, transcodeClass));
}
 
Example 3
Source File: GenericRequestBuilder.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Set the target the resource will be loaded into.
 *
 * @see Glide#clear(Target)
 *
 * @param target The target to load the resource into.
 * @return The given target.
 */
public <Y extends Target<TranscodeType>> Y into(Y target) {
    Util.assertMainThread();
    if (target == null) {
        throw new IllegalArgumentException("You must pass in a non null Target");
    }
    if (!isModelSet) {
        throw new IllegalArgumentException("You must first set a model (try #load())");
    }

    Request previous = target.getRequest();

    if (previous != null) {
        previous.clear();
        requestTracker.removeRequest(previous);
        previous.recycle();
    }

    Request request = buildRequest(target);
    target.setRequest(request);
    lifecycle.addListener(target);
    requestTracker.runRequest(request);

    return target;
}
 
Example 4
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void onResourceReleased(Key cacheKey, EngineResource resource) {
    Util.assertMainThread();
    activeResources.remove(cacheKey);
    if (resource.isCacheable()) {
        cache.put(cacheKey, resource);
    } else {
        resourceRecycler.recycle(resource);
    }
}
 
Example 5
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void onEngineJobCancelled(EngineJob engineJob, Key key) {
    Util.assertMainThread();
    EngineJob current = jobs.get(key);
    if (engineJob.equals(current)) {
        jobs.remove(key);
    }
}
 
Example 6
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void onEngineJobComplete(Key key, EngineResource<?> resource) {
    Util.assertMainThread();
    // A null resource indicates that the load failed, usually due to an exception.
    if (resource != null) {
        resource.setResourceListener(key, this);

        if (resource.isCacheable()) {
            activeResources.put(key, new ResourceWeakReference(key, resource, getReferenceQueue()));
        }
    }
    // TODO: should this check that the engine job is still current?
    jobs.remove(key);
}
 
Example 7
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void release(Resource resource) {
    Util.assertMainThread();
    if (resource instanceof EngineResource) {
        ((EngineResource) resource).release();
    } else {
        throw new IllegalArgumentException("Cannot release anything but an EngineResource");
    }
}
 
Example 8
Source File: EngineJob.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void removeCallback(ResourceCallback cb) {
    Util.assertMainThread();
    if (hasResource || hasException) {
        addIgnoredCallback(cb);
    } else {
        cbs.remove(cb);
        if (cbs.isEmpty()) {
            cancel();
        }
    }
}
 
Example 9
Source File: EngineJob.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void addCallback(ResourceCallback cb) {
    Util.assertMainThread();
    if (hasResource) {
        cb.onResourceReady(engineResource);
    } else if (hasException) {
        cb.onException(exception);
    } else {
        cbs.add(cb);
    }
}
 
Example 10
Source File: ResourceRecycler.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void recycle(Resource<?> resource) {
    Util.assertMainThread();

    if (isRecycling) {
        // If a resource has sub-resources, releasing a sub resource can cause it's parent to be synchronously
        // evicted which leads to a recycle loop when the parent releases it's children. Posting breaks this loop.
        handler.obtainMessage(ResourceRecyclerCallback.RECYCLE_RESOURCE, resource).sendToTarget();
    } else {
        isRecycling = true;
        resource.recycle();
        isRecycling = false;
    }
}
 
Example 11
Source File: Glide.java    From giffun with Apache License 2.0 5 votes vote down vote up
/**
 * Cancel any pending loads Glide may have for the target and free any resources (such as {@link Bitmap}s) that may
 * have been loaded for the target so they may be reused.
 *
 * @param target The Target to cancel loads for.
 */
public static void clear(Target<?> target) {
    Util.assertMainThread();
    Request request = target.getRequest();
    if (request != null) {
        request.clear();
        target.setRequest(null);
    }
}
 
Example 12
Source File: Glide.java    From giffun with Apache License 2.0 5 votes vote down vote up
/**
 * Clears some memory with the exact amount depending on the given level.
 *
 * @see android.content.ComponentCallbacks2#onTrimMemory(int)
 */
public void trimMemory(int level) {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be trimmed before bitmap pool to trim re-pooled Bitmaps too. See #687.
    memoryCache.trimMemory(level);
    bitmapPool.trimMemory(level);
}
 
Example 13
Source File: Glide.java    From giffun with Apache License 2.0 5 votes vote down vote up
/**
 * Clears as much memory as possible.
 *
 * @see android.content.ComponentCallbacks#onLowMemory()
 * @see android.content.ComponentCallbacks2#onLowMemory()
 */
public void clearMemory() {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be cleared before bitmap pool to clear re-pooled Bitmaps too. See #687.
    memoryCache.clearMemory();
    bitmapPool.clearMemory();
}
 
Example 14
Source File: RequestManager.java    From giffun with Apache License 2.0 5 votes vote down vote up
/**
 * Performs {@link #resumeRequests()} recursively for all managers that are contextually descendant
 * to this manager based on the Activity/Fragment hierarchy. The hierarchical semantics are identical as for
 * {@link #pauseRequestsRecursive()}.
 */
public void resumeRequestsRecursive() {
    Util.assertMainThread();
    resumeRequests();
    for (RequestManager requestManager : treeNode.getDescendants()) {
        requestManager.resumeRequests();
    }
}
 
Example 15
Source File: Engine.java    From giffun with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a load for the given arguments. Must be called on the main thread.
 *
 * <p>
 *     The flow for any request is as follows:
 *     <ul>
 *         <li>Check the memory cache and provide the cached resource if present</li>
 *         <li>Check the current set of actively used resources and return the active resource if present</li>
 *         <li>Check the current set of in progress loads and add the cb to the in progress load if present</li>
 *         <li>Start a new load</li>
 *     </ul>
 * </p>
 *
 * <p>
 *     Active resources are those that have been provided to at least one request and have not yet been released.
 *     Once all consumers of a resource have released that resource, the resource then goes to cache. If the
 *     resource is ever returned to a new consumer from cache, it is re-added to the active resources. If the
 *     resource is evicted from the cache, its resources are recycled and re-used if possible and the resource is
 *     discarded. There is no strict requirement that consumers release their resources so active resources are
 *     held weakly.
 * </p>
 *
 * @param signature A non-null unique key to be mixed into the cache key that identifies the version of the data to
 *                  be loaded.
 * @param width The target width in pixels of the desired resource.
 * @param height The target height in pixels of the desired resource.
 * @param fetcher The fetcher to use to retrieve data not in the disk cache.
 * @param loadProvider The load provider containing various encoders and decoders use to decode and encode data.
 * @param transformation The transformation to use to transform the decoded resource.
 * @param transcoder The transcoder to use to transcode the decoded and transformed resource.
 * @param priority The priority with which the request should run.
 * @param isMemoryCacheable True if the transcoded resource can be cached in memory.
 * @param diskCacheStrategy The strategy to use that determines what type of data, if any,
 *                          will be cached in the local disk cache.
 * @param cb The callback that will be called when the load completes.
 *
 * @param <T> The type of data the resource will be decoded from.
 * @param <Z> The type of the resource that will be decoded.
 * @param <R> The type of the resource that will be transcoded from the decoded resource.
 */
public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,
        DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,
        Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {
    Util.assertMainThread();
    long startTime = LogTime.getLogTime();

    final String id = fetcher.getId();
    EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),
            loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),
            transcoder, loadProvider.getSourceEncoder());

    EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
        cb.onResourceReady(cached);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Loaded resource from cache", startTime, key);
        }
        return null;
    }

    EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
        cb.onResourceReady(active);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Loaded resource from active resources", startTime, key);
        }
        return null;
    }

    EngineJob current = jobs.get(key);
    if (current != null) {
        current.addCallback(cb);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Added to existing load", startTime, key);
        }
        return new LoadStatus(cb, current);
    }

    EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);
    DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation,
            transcoder, diskCacheProvider, diskCacheStrategy, priority);
    EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
    jobs.put(key, engineJob);
    engineJob.addCallback(cb);
    engineJob.start(runnable);

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Started new load", startTime, key);
    }
    return new LoadStatus(cb, engineJob);
}
 
Example 16
Source File: Engine.java    From giffun with Apache License 2.0 4 votes vote down vote up
@Override
public void onResourceRemoved(final Resource<?> resource) {
    Util.assertMainThread();
    resourceRecycler.recycle(resource);
}
 
Example 17
Source File: Glide.java    From giffun with Apache License 2.0 3 votes vote down vote up
/**
 * Adjusts Glide's current and maximum memory usage based on the given {@link MemoryCategory}.
 *
 * <p>
 *     The default {@link MemoryCategory} is {@link MemoryCategory#NORMAL}. {@link MemoryCategory#HIGH} increases
 *     Glide's maximum memory usage by up to 50% and {@link MemoryCategory#LOW} decreases Glide's maximum memory
 *     usage by 50%. This method should be used to temporarily increase or decrease memory useage for a single
 *     Activity or part of the app. Use {@link GlideBuilder#setMemoryCache(MemoryCache)} to set a permanent
 *     memory size if you want to change the default.
 * </p>
 */
public void setMemoryCategory(MemoryCategory memoryCategory) {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be trimmed before bitmap pool to trim re-pooled Bitmaps too. See #687.
    memoryCache.setSizeMultiplier(memoryCategory.getMultiplier());
    bitmapPool.setSizeMultiplier(memoryCategory.getMultiplier());
}
 
Example 18
Source File: RequestManager.java    From giffun with Apache License 2.0 3 votes vote down vote up
/**
 * Performs {@link #pauseRequests()} recursively for all managers that are contextually descendant
 * to this manager based on the Activity/Fragment hierarchy:
 *
 * <ul>
 * <li>When pausing on an Activity all attached fragments will also get paused.
 * <li>When pausing on an attached Fragment all descendant fragments will also get paused.
 * <li>When pausing on a detached Fragment or the application context only the current RequestManager is paused.
 * </ul>
 *
 * <p>Note, on pre-Jelly Bean MR1 calling pause on a Fragment will not cause child fragments to pause, in this
 * case either call pause on the Activity or use a support Fragment.
 */
public void pauseRequestsRecursive() {
    Util.assertMainThread();
    pauseRequests();
    for (RequestManager requestManager : treeNode.getDescendants()) {
        requestManager.pauseRequests();
    }
}
 
Example 19
Source File: RequestManager.java    From giffun with Apache License 2.0 2 votes vote down vote up
/**
 * Restarts any loads that have not yet completed.
 *
 * @see #isPaused()
 * @see #pauseRequests()
 */
public void resumeRequests() {
    Util.assertMainThread();
    requestTracker.resumeRequests();
}
 
Example 20
Source File: RequestManager.java    From giffun with Apache License 2.0 2 votes vote down vote up
/**
 * Cancels any in progress loads, but does not clear resources of completed loads.
 *
 * @see #isPaused()
 * @see #resumeRequests()
 */
public void pauseRequests() {
    Util.assertMainThread();
    requestTracker.pauseRequests();
}