Serialize image downloading

This prevents slow connections from being saturized and causes cached images to be reused
pull/156/head
M66B 6 years ago
parent 50434e744f
commit 4cac61b03b

@ -81,7 +81,7 @@ public class HtmlHelper {
private static final List<String> tails = Collections.unmodifiableList(Arrays.asList(
"h1", "h2", "h3", "h4", "h5", "h6", "p", "ol", "ul", "li"));
private static final ExecutorService executor = Executors.newCachedThreadPool(Helper.backgroundThreadFactory);
private static final ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
static String removeTracking(Context context, String html) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@ -268,7 +268,7 @@ public class HtmlHelper {
return (body == null ? "" : body.html());
}
static Drawable decodeImage(final String source, long id, boolean show, final TextView view) {
static Drawable decodeImage(final String source, final long id, boolean show, final TextView view) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(view.getContext());
boolean compact = prefs.getBoolean("compact", false);
int zoom = prefs.getInt("zoom", compact ? 0 : 1);
@ -351,36 +351,35 @@ public class HtmlHelper {
return d;
}
// Get cache file name
File dir = new File(view.getContext().getCacheDir(), "images");
if (!dir.exists())
dir.mkdir();
final File file = new File(dir, id + "_" + Math.abs(source.hashCode()) + ".png");
if (file.exists()) {
Log.i("Using cached " + file);
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bm == null) {
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
d.setBounds(0, 0, px, px);
return d;
} else {
Drawable d = new BitmapDrawable(res, bm);
d.setBounds(0, 0, bm.getWidth(), bm.getHeight());
return d;
}
}
final LevelListDrawable lld = new LevelListDrawable();
Drawable wait = res.getDrawable(R.drawable.baseline_hourglass_empty_24, theme);
lld.addLevel(0, 0, wait);
lld.setBounds(0, 0, px, px);
final Context context = view.getContext().getApplicationContext();
final Handler handler = new Handler(view.getContext().getMainLooper());
executor.submit(new Runnable() {
@Override
public void run() {
try {
// Get cache file name
File dir = new File(context.getCacheDir(), "images");
if (!dir.exists())
dir.mkdir();
File file = new File(dir, id + "_" + Math.abs(source.hashCode()) + ".png");
// Get cached image
if (file.exists() && !BuildConfig.DEBUG) {
Log.i("Using cached " + file);
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bm != null) {
Drawable d = new BitmapDrawable(res, bm);
d.setBounds(0, 0, bm.getWidth(), bm.getHeight());
post(d, source);
return;
}
}
BitmapFactory.Options options = new BitmapFactory.Options();
Log.i("Probe " + source);
try (InputStream probe = new URL(source).openStream()) {

Loading…
Cancel
Save