Repository navigation
Expand file tree
/
Copy pathWebImage.java
More file actions
64 lines (51 loc) · 1.63 KB
/
Copy pathWebImage.java
File metadata and controls
64 lines (51 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.loopj.android.image;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class WebImage implements SmartImage {
private static final int CONNECT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 10000;
private static WebImageCache webImageCache;
private String url;
public WebImage(String url) {
this.url = url;
}
public Bitmap getBitmap(Context context) {
// Don't leak context
if(webImageCache == null) {
webImageCache = new WebImageCache(context);
}
// Try getting bitmap from cache first
Bitmap bitmap = null;
if(url != null) {
bitmap = webImageCache.get(url);
if(bitmap == null) {
bitmap = getBitmapFromUrl(url);
if(bitmap != null){
webImageCache.put(url, bitmap);
}
}
}
return bitmap;
}
private Bitmap getBitmapFromUrl(String url) {
Bitmap bitmap = null;
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
public static void removeFromCache(String url) {
if(webImageCache != null) {
webImageCache.remove(url);
}
}
}