public
Created

  • Download Gist
ImageContentProvider.java
Java
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
public class ImageContentProvider extends ContentProvider {
 
private static final String URI_PREFIX = "content://com.xianguo.image/";
 
public static String constructUri(String imageUrl) {
return URI_PREFIX + Uri.encode(imageUrl);
}
 
public static String deconstructUri(String imageUrl) {
if (imageUrl == null || !imageUrl.startsWith(URI_PREFIX)) {
return imageUrl;
}
imageUrl = imageUrl.substring(URI_PREFIX.length());
return Uri.decode(imageUrl);
}
 
public static String deconstructUri(Uri uri) {
String imageUrl = uri.toString();
return deconstructUri(imageUrl);
}
 
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String imageUrl = deconstructUri(uri);
ImageCache imageCache = ImageCache.getInstance(getContext());
 
if (!imageCache.containsInDisk(imageUrl)) {
byte[] imageData = downloadImage(imageUrl);
if (imageData != null) {
imageCache.cacheToDisk(imageUrl, imageData);
}
}
String path = imageCache.getFilePathInDisk(imageUrl);
if (path != null) {
File file = new File(path);
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
return null;
}
 
/**
* Download From Internet
* @param imageUrl
*/
protected byte[] downloadImage(String imageUrl) {
try {
return HttpClient.doRequest(imageUrl, null);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
 
@Override
public boolean onCreate() {
return true;
}
 
@Override
public int delete(Uri uri, String s, String[] as) {
throw new UnsupportedOperationException("Not supported by this provider");
}
 
@Override
public String getType(Uri uri) {
throw new UnsupportedOperationException("Not supported by this provider");
}
 
@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
throw new UnsupportedOperationException("Not supported by this provider");
}
 
@Override
public Cursor query(Uri uri, String[] as, String s, String[] as1, String s1) {
throw new UnsupportedOperationException("Not supported by this provider");
}
 
@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
throw new UnsupportedOperationException("Not supported by this provider");
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.