下面列出了怎么用com.bumptech.glide.load.data.DataFetcher的API类实例代码及写法,或者点击链接到github查看源代码。
DecodeJob(EngineKey resultKey, int width, int height, DataFetcher<A> fetcher,
DataLoadProvider<A, T> loadProvider, Transformation<T> transformation, ResourceTranscoder<T, Z> transcoder,
DiskCacheProvider diskCacheProvider, DiskCacheStrategy diskCacheStrategy, Priority priority, FileOpener
fileOpener) {
this.resultKey = resultKey;
this.width = width;
this.height = height;
this.fetcher = fetcher;
this.loadProvider = loadProvider;
this.transformation = transformation;
this.transcoder = transcoder;
this.diskCacheProvider = diskCacheProvider;
this.diskCacheStrategy = diskCacheStrategy;
this.priority = priority;
this.fileOpener = fileOpener;
}
@Override
public DataFetcher<T> getResourceFetcher(String model, int width, int height) {
Uri uri;
if (TextUtils.isEmpty(model)) {
return null;
} else if (model.startsWith("/")) {
uri = toFileUri(model);
} else {
uri = Uri.parse(model);
final String scheme = uri.getScheme();
if (scheme == null) {
uri = toFileUri(model);
}
}
return uriLoader.getResourceFetcher(uri, width, height);
}
@Override
public DataFetcher<ImageVideoWrapper> getResourceFetcher(A model, int width, int height) {
DataFetcher<InputStream> streamFetcher = null;
if (streamLoader != null) {
streamFetcher = streamLoader.getResourceFetcher(model, width, height);
}
DataFetcher<ParcelFileDescriptor> fileDescriptorFetcher = null;
if (fileDescriptorLoader != null) {
fileDescriptorFetcher = fileDescriptorLoader.getResourceFetcher(model, width, height);
}
if (streamFetcher != null || fileDescriptorFetcher != null) {
return new ImageVideoFetcher(streamFetcher, fileDescriptorFetcher);
} else {
return null;
}
}
@Override
public final DataFetcher<T> getResourceFetcher(Uri model, int width, int height) {
final String scheme = model.getScheme();
DataFetcher<T> result = null;
if (isLocalUri(scheme)) {
if (AssetUriParser.isAssetUri(model)) {
String path = AssetUriParser.toAssetPath(model);
result = getAssetPathFetcher(context, path);
} else {
result = getLocalUriFetcher(context, model);
}
} else if (urlLoader != null && ("http".equals(scheme) || "https".equals(scheme))) {
result = urlLoader.getResourceFetcher(new GlideUrl(model.toString()), width, height);
}
return result;
}
@Override
public DataFetcher<T> getResourceFetcher(Integer model, int width, int height) {
Uri uri = null;
try {
uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ resources.getResourcePackageName(model) + '/'
+ resources.getResourceTypeName(model) + '/'
+ resources.getResourceEntryName(model));
} catch (Resources.NotFoundException e) {
if (Log.isLoggable(TAG, Log.WARN)) {
Log.w(TAG, "Received invalid resource id: " + model, e);
}
}
if (uri != null) {
return uriLoader.getResourceFetcher(uri, width, height);
} else {
return null;
}
}
@Override
public DataFetcher<InputStream> getResourceFetcher(final String model, int i, int i1) {
return new DataFetcher<InputStream>() {
@Override
public InputStream loadData(Priority priority) {
return null;
}
@Override
public void cleanup() {
}
@Override
public String getId() {
return model;
}
@Override
public void cancel() {
}
};
}
@Override
public DataFetcher<InputStream> getResourceFetcher(final String model, int width, int height) {
return new DataFetcher<InputStream>() {
@Override
public InputStream loadData(Priority priority) throws Exception {
throw new IOException("Forced Glide network failure");
}
@Override
public void cleanup() {
}
@Override
public String getId() {
return model;
}
@Override
public void cancel() {
}
};
}
/**
* A callback method that should never be invoked directly.
*/
@Override
public void onSizeReady(int width, int height) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logV("Got onSizeReady in " + LogTime.getElapsedMillis(startTime));
}
if (status != Status.WAITING_FOR_SIZE) {
return;
}
status = Status.RUNNING;
width = Math.round(sizeMultiplier * width);
height = Math.round(sizeMultiplier * height);
ModelLoader<A, T> modelLoader = loadProvider.getModelLoader();
final DataFetcher<T> dataFetcher = modelLoader.getResourceFetcher(model, width, height);
if (dataFetcher == null) {
onException(new Exception("Failed to load model: \'" + model + "\'"));
return;
}
ResourceTranscoder<Z, R> transcoder = loadProvider.getTranscoder();
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logV("finished setup for calling load in " + LogTime.getElapsedMillis(startTime));
}
loadedFromMemoryCache = true;
loadStatus = engine.load(signature, width, height, dataFetcher, loadProvider, transformation, transcoder,
priority, isMemoryCacheable, diskCacheStrategy, this);
loadedFromMemoryCache = resource != null;
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
}
}
@Override
public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
// GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time spent parsing urls.
GlideUrl url = model;
if (modelCache != null) {
url = modelCache.get(model, 0, 0);
if (url == null) {
modelCache.put(model, 0, 0, model);
url = model;
}
}
return new HttpUrlFetcher(url);
}
@Override
public DataFetcher<InputStream> getResourceFetcher(String model, int width, int height) {
String result = null;
if (modelCache != null) {
result = modelCache.get(model, width, height);
}
if (result == null) {
result = model;
if (modelCache != null) {
modelCache.put(model, width, height, result);
}
}
return new ProgressDataFetcher(result, handler);
}
@Override
public void loadData(@NonNull Priority priority,
@NonNull final DataFetcher.DataCallback<? super InputStream> callback) {
Request.Builder requestBuilder = new Request.Builder().url(mGlideUrl.toStringUrl());
for (Map.Entry<String, String> headerEntry : mGlideUrl.getHeaders().entrySet()) {
String key = headerEntry.getKey();
requestBuilder.addHeader(key, headerEntry.getValue());
}
Request request = requestBuilder.build();
mDataCallback = callback;
mCall = mCallFactory.newCall(request);
mCall.enqueue(this);
}
@Override
public DataFetcher<InputStream> getResourceFetcher(String model, int width, int height) {
String result = null;
if (modelCache != null) {
result = modelCache.get(model, width, height);
}
if (result == null) {
result = model;
if (modelCache != null) {
modelCache.put(model, width, height, result);
}
}
return new ProgressDataFetcher(result, handler);
}
/**
* load cache image with Glide
*/
private void loadCache(Context ctx, ImageLoader img) {
Glide.with(ctx).using(new StreamModelLoader<String>() {
@Override
public DataFetcher<InputStream> getResourceFetcher(final String model, int i, int i1) {
return new DataFetcher<InputStream>() {
@Override
public InputStream loadData(Priority priority) throws Exception {
throw new IOException();
}
@Override
public void cleanup() {
}
@Override
public String getId() {
return model;
}
@Override
public void cancel() {
}
};
}
}).load(img.getUrl()).placeholder(img.getPlaceHolder()).diskCacheStrategy(DiskCacheStrategy.ALL).into(img.getImgView());
}
@Override public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
SharedPreferences prefs = App.getPrefs();
if (prefs.getBoolean("wifi_only", false)) {
return new NetworkDisablingFetcher(model);
} else {
return defaultLoader.getResourceFetcher(model, width, height);
}
}
@Override public DataFetcher<InputStream> getResourceFetcher(final FirebaseImage model, int width, int height) {
return new DataFetcher<InputStream>() {
private Thread decodingThread;
@Override public InputStream loadData(Priority priority) throws Exception {
decodingThread = Thread.currentThread();
// somehow make sure that fb is ready after authWithPassword is called
String dataUri = model.getDataUri(fb);
String base64 = dataUri.substring("data:image/jpeg;base64,".length());
// depending on how you encoded it, the below is just a guess:
// here the full base64 is decoded into bytes and the bytes will be parsed by Glide
return new ByteArrayInputStream(Base64.decode(base64, Base64.NO_WRAP | Base64.URL_SAFE));
// if you don't want to delay decoding you can use something like:
// Base64InputStream (http://stackoverflow.com/a/19981216/253468)
// here the base64 bytes are passed to Base64InputStream and that to Glide
// so base64 decoding will be done later when Glide reads from the stream.
//return new Base64InputStream(new ByteArrayInputStream(base64.getBytes("utf-8")), Base64.NO_WRAP | Base64.URL_SAFE);
}
@Override public String getId() {
return model.key; // for cache
}
@Override public void cancel() {
// don't do this if it's likely to display in the future (read doc of cancel)
decodingThread.interrupt(); // should fly out from await()
}
@Override public void cleanup() {
decodingThread = null;
}
};
}
@Override public DataFetcher<InputStream> getResourceFetcher(final String model, int width, int height) {
if (model.startsWith(PREFIX)) { // TODO better matching based on your needs
return new Base64StreamDataFetcher(model.substring(PREFIX.length()));
} else {
return defaultLoader.getResourceFetcher(model, width, height);
}
}
@Override public DataFetcher<InputStream> getResourceFetcher(final YouTubeVideo model, final int width,
final int height) {
return new DataFetcher<InputStream>() {
private DataFetcher<InputStream> fetcher;
@Override public String getId() {
return model.id; // assuming that if SDUrl failed once, it'll fail the next time
// so it's better to cache MDUrl in that case for this video, forever
}
@Override public InputStream loadData(Priority priority) throws Exception {
try {
fetcher = loader.getResourceFetcher(model.getSDUrl(), width, height);
return fetcher.loadData(priority);
} catch (Exception ex) {
if (fetcher != null) {
fetcher.cleanup();
}
fetcher = loader.getResourceFetcher(model.getMDUrl(), width, height);
return fetcher.loadData(priority);
}
}
@Override public void cleanup() {
if (fetcher != null) {
fetcher.cleanup();
}
}
@Override public void cancel() {
if (fetcher != null) {
fetcher.cancel();
}
}
};
}
@Override public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
// GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time spent parsing urls.
GlideUrl url = model;
if (modelCache != null) {
url = modelCache.get(model, 0, 0);
if (url == null) {
modelCache.put(model, 0, 0, model);
url = model;
}
}
return new StethoHttpUrlFetcher(url);
}
@Override public DataFetcher<GenerateParams> getResourceFetcher(final GenerateParams model, int width, int height) {
return new DataFetcher<GenerateParams>() {
@Override public GenerateParams loadData(Priority priority) throws Exception {
return model;
}
@Override public void cleanup() {
}
@Override public String getId() {
return model.getId();
}
@Override public void cancel() {
}
};
}
@Override
public DataFetcher<GifDecoder> getResourceFetcher(GifDecoder model, int width, int height) {
return new GifFrameDataFetcher(model);
}
public DecodeJob(EngineKey resultKey, int width, int height, DataFetcher<A> fetcher,
DataLoadProvider<A, T> loadProvider, Transformation<T> transformation, ResourceTranscoder<T, Z> transcoder,
DiskCacheProvider diskCacheProvider, DiskCacheStrategy diskCacheStrategy, Priority priority) {
this(resultKey, width, height, fetcher, loadProvider, transformation, transcoder, diskCacheProvider,
diskCacheStrategy, priority, DEFAULT_FILE_OPENER);
}
/**
* 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);
}
@Override
public DataFetcher<InputStream> getResourceFetcher(byte[] model, int width, int height) {
return new ByteArrayFetcher(model, id);
}
@Override
public DataFetcher<InputStream> getResourceFetcher(Uri model, int width, int height) {
return new MediaStoreThumbFetcher(context, model, uriLoader.getResourceFetcher(model, width, height), width,
height);
}
@Override
protected DataFetcher<InputStream> getLocalUriFetcher(Context context, Uri uri) {
return new StreamLocalUriFetcher(context, uri);
}
@Override
protected DataFetcher<InputStream> getAssetPathFetcher(Context context, String assetPath) {
return new StreamAssetPathFetcher(context.getApplicationContext().getAssets(), assetPath);
}
@Override
public DataFetcher<T> getResourceFetcher(URL model, int width, int height) {
return glideUrlLoader.getResourceFetcher(new GlideUrl(model), width, height);
}
@Override
protected DataFetcher<ParcelFileDescriptor> getLocalUriFetcher(Context context, Uri uri) {
return new FileDescriptorLocalUriFetcher(context, uri);
}
@Override
protected DataFetcher<ParcelFileDescriptor> getAssetPathFetcher(Context context, String assetPath) {
return new FileDescriptorAssetPathFetcher(context.getApplicationContext().getAssets(), assetPath);
}
public ImageVideoFetcher(DataFetcher<InputStream> streamFetcher,
DataFetcher<ParcelFileDescriptor> fileDescriptorFetcher) {
this.streamFetcher = streamFetcher;
this.fileDescriptorFetcher = fileDescriptorFetcher;
}