//the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap
final String TAG="ReflectedImageLoader";
private File cacheDir;
public ReflectedImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY+3); //changed the thread priority
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"sample/categories");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id=R.drawable.icon;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
Log.e(TAG, "URL for image loading - "+url);
url=url.replace("https", "http");
if(cache.containsKey(url)){
imageView.setImageBitmap(cache.get(url));
Log.e(TAG, "IMG Available");
System.gc();
//this.stopThread();
}else
{
Log.e(TAG, "Put on Queue");
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url)
{
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
File f=new File(cacheDir, filename);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept","text/html");
httpget.setHeader("Accept-Encoding","gzip,deflate");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
Log.e(TAG, "StatusCode() "+response.getStatusLine().getStatusCode());
if(entity==null||response.getStatusLine().getStatusCode()==404){
Log.e(TAG, "Empty Response for "+url);
return null;
}
InputStream is = entity.getContent();
// InputStream is=new URL(url).openStream();
No comments:
Post a Comment