下面列出了com.bumptech.glide.load.resource.file.FileToStreamDecoder#com.bumptech.glide.signature.StringSignature 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override protected void load(final Context context) throws Exception {
String profileUrl = "...";
long lastProfileCache = context.getSharedPreferences("profile", 0)
.getLong("lastCacheTime", System.currentTimeMillis());
Glide // display a fresh version
.with(context)
.load(profileUrl)
.thumbnail(Glide // display a cached version
.with(context)
.using(new NetworkDisablingLoader<>()) // only if exists in disk cache
.load(profileUrl)
.signature(new StringSignature(String.valueOf(lastProfileCache)))
.diskCacheStrategy(SOURCE)
)
.diskCacheStrategy(NONE) // downloaded right now
.into(imageView)
;
}
private void cache(String url, final Bitmap bitmap) {
Key key = new StringSignature(url);
// the key here is that Engine uses fetcher.getId() for constructing OriginalKey from EngineKey
// see Engine.load and also signature can be ignored because it is an EmptySignature instance for most
App.getInstance().getDiskCache().put(key, new Writer() {
@TargetApi(VERSION_CODES.KITKAT) // for try-with-resources
@Override public boolean write(File file) {
try (OutputStream out = new FileOutputStream(file)) {
// mimic default behavior you can also use Bitmap.compress
BitmapPool pool = Glide.get(getContext()).getBitmapPool();
BitmapResource resource = BitmapResource.obtain(bitmap, pool);
new BitmapEncoder().encode(resource, out);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
});
}
@SuppressWarnings("unchecked")
@Override protected void load(Context context) {
GenericRequestBuilder<Bitmap, Bitmap, Bitmap, Bitmap> glide = Glide
.with(context)
.using(new PassthroughModelLoader<Bitmap, Bitmap>(), Bitmap.class)
.from(Bitmap.class)
.as(Bitmap.class)
.decoder(new BitmapBitmapResourceDecoder(context))
.cacheDecoder(new FileToStreamDecoder<Bitmap>(new StreamBitmapDecoder(context)))
.encoder(new BitmapEncoder())
// or .diskCacheStrategy(DiskCacheStrategy.NONE) instead of last 2
;
// simulate a bitmap input
Drawable drawable = ContextCompat.getDrawable(context, android.R.drawable.sym_def_app_icon);
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
glide
.clone()
.load(bitmap)
.signature(new StringSignature("android.R.drawable.sym_def_app_icon")) // required for caching
.diskCacheStrategy(DiskCacheStrategy.NONE) // but can't really cache it, see #122 comments
.transform(new CenterCrop(context))
.into(imageView)
;
}
private void updateProfileCache(final Context context, String profileUrl) {
final long lastProfileCache = System.currentTimeMillis();
Glide
.with(context)
.load(profileUrl)
.signature(new StringSignature(String.valueOf(lastProfileCache)))
.diskCacheStrategy(SOURCE)
.listener(new SaveLastProfileCacheTime(context, lastProfileCache))
.preload()
;
}
@Override protected void load(final Context context) throws Exception {
final ImageView imageView = this.imageView;
toto = toto + 1;
Glide
.with(context.getApplicationContext())
.load("http://lorempixel.com/400/200/sports")
.signature(new StringSignature(Integer.toString(toto)))
.centerCrop()
.listener(new LoggingListener<String, GlideDrawable>())
.into(imageView)
;
}
@Override protected void load1(Context context, ImageView imageView) throws Exception {
Glide
.with(this)
// default timeout is 2.5 seconds (com.bumptech.glide.load.data.HttpUrlFetcher)
.load("https://httpbin.org/delay/12") // force a timeout: 2.5 < 12
.signature(new StringSignature("load1")) // distinguish from other load to make sure loader is picked up
.placeholder(R.drawable.glide_placeholder)
.error(R.drawable.glide_error)
.listener(new LoggingListener<String, GlideDrawable>("load1"))
.into(new LoggingTarget<>("load1", Log.VERBOSE, new GlideDrawableImageViewTarget(imageView)))
;
}
@Override protected void load2(Context context, ImageView imageView) throws Exception {
Glide
.with(this)
.using(new StreamModelLoaderWrapper<>(new OkHttpUrlLoader(longTimeoutClient)))
.load(new GlideUrl("https://httpbin.org/delay/12")) // timeout increased: 15 > 10, so it'll pass
.signature(new StringSignature("load2")) // distinguish from other load to make sure loader is picked up
.placeholder(R.drawable.glide_placeholder)
// since the test URL returns a JSON stream, the load will fail,
// let's still add an error to see that the load fails slower than the other,
// meaning the image was actually tried to be decoded
.error(R.drawable.glide_error)
.listener(new LoggingListener<GlideUrl, GlideDrawable>("load2"))
.into(new LoggingTarget<>("load2", Log.VERBOSE, new GlideDrawableImageViewTarget(imageView)))
;
}
public StringSignature getArtistSignature(String artistName) {
return new StringSignature(String.valueOf(getArtistSignatureRaw(artistName)));
}
public StringSignature getArtistSignature(String artistName) {
return new StringSignature(String.valueOf(getArtistSignatureRaw(artistName)));
}
public StringSignature getArtistSignature(String artistName) {
return new StringSignature(String.valueOf(getArtistSignatureRaw(artistName)));
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
viewHolder.itemView.setClickable(true);
viewHolder.itemView.setActivated(mSelectedItems.get(position, false));
entry = mItems.get(position);
date = entry.creationDate;
description = entry.text;
tags = entry.tags;
starred = entry.starred;
emptyCal.set(Calendar.DAY_OF_MONTH, date.get(Calendar.DAY_OF_MONTH));
emptyCal.set(Calendar.MONTH, date.get(Calendar.MONTH));
emptyCal.set(Calendar.YEAR, date.get(Calendar.YEAR));
viewHolder.title.setText(entry.title);
if (description != null)
viewHolder.description.setText(description.substring(0, Math.min(description.length(), 400)));
viewHolder.timeOfDay.setText(timeFormat.format(date.getTime()));
if (entry.photos.isEmpty()) {
viewHolder.thumbnail.setVisibility(View.GONE);
viewHolder.dayOfMonth.setVisibility(View.VISIBLE);
viewHolder.dayOfMonth.setText(String.valueOf(entry.creationDate.get(Calendar.DAY_OF_MONTH)));
if (!colorDates.contains(emptyCal.getTimeInMillis())) {
int index = mBackgroundCount++ % mCircleBackgrounds.length;
if (Build.VERSION.SDK_INT >= 16)
viewHolder.dayOfMonth.setBackground(mCircleBackgrounds[index]);
else
viewHolder.dayOfMonth.setBackgroundDrawable(mCircleBackgrounds[index]);
viewHolder.dayOfMonth.setTag(index);
colorMap.put(emptyCal.getTimeInMillis(), index);
colorDates.add(emptyCal.getTimeInMillis());
} else {
if (Build.VERSION.SDK_INT >= 16)
viewHolder.dayOfMonth.setBackground(mCircleBackgrounds[colorMap.get(emptyCal.getTimeInMillis())]);
else
viewHolder.dayOfMonth.setBackgroundDrawable(mCircleBackgrounds[colorMap.get(emptyCal.getTimeInMillis())]);
}
} else {
viewHolder.dayOfMonth.setVisibility(View.GONE);
viewHolder.thumbnail.setVisibility(View.VISIBLE);
String path = entry.photos.get(0).path;
File image = new File(path);
Glide.with(GlobalApplication.getAppContext())
.load(path)
.transform(mRoundCornerTransformation)
.placeholder(R.color.transparent)
.signature(new StringSignature(String.valueOf(image.lastModified())))
.into(viewHolder.thumbnail);
}
if (starred) {
viewHolder.bookmark.setVisibility(View.VISIBLE);
} else {
viewHolder.bookmark.setVisibility(View.INVISIBLE);
}
}
public StringSignature getArtistSignature(String artistName) {
return new StringSignature(String.valueOf(getArtistSignatureRaw(artistName)));
}
/**
* Returns a request builder that uses {@link StreamByteArrayLoader} to load
* images from byte arrays.
*
* <p>
* Note - by default loads for bytes are not cached in either the memory or the disk cache.
* </p>
*
* @see #from(Class)
* @see #load(byte[])
*/
public DrawableTypeRequest<byte[]> fromBytes() {
return (DrawableTypeRequest<byte[]>) loadGeneric(byte[].class)
.signature(new StringSignature(UUID.randomUUID().toString()))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true /*skipMemoryCache*/);
}
/**
* Returns a request builder that uses a {@link StreamByteArrayLoader} to load an image from the given byte array.
*
*
* <p>
* Note - by default loads for bytes are not cached in either the memory or the disk cache.
* </p>
*
* @see #load(byte[])
*
* @deprecated Use {@link #load(byte[])} along with
* {@link GenericRequestBuilder#signature(Key)} instead. Scheduled to be
* removed in Glide 4.0.
* @param model The data to load.
* @param id A unique id that identifies the image represented by the model suitable for use as a cache key
* (url, filepath etc). If there is no suitable id, use {@link #load(byte[])} instead.
*/
@Deprecated
public DrawableTypeRequest<byte[]> load(byte[] model, final String id) {
return (DrawableTypeRequest<byte[]>) load(model).signature(new StringSignature(id));
}