Guest User

Untitled

a guest
Jan 21st, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.01 KB | None | 0 0
  1. package com.warriorpoint.androidxmlsimple;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.HttpURLConnection;
  10. import java.util.ArrayList;
  11. import java.util.Hashtable;
  12.  
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.HttpResponse;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.params.HttpClientParams;
  17. import org.apache.http.params.BasicHttpParams;
  18. import org.apache.http.params.HttpParams;
  19.  
  20. import android.app.Activity;
  21.  
  22. import android.content.Context;
  23. import android.content.res.AssetManager;
  24. import android.content.res.Resources;
  25. import android.graphics.Bitmap;
  26. import android.graphics.BitmapFactory;
  27. import android.graphics.drawable.BitmapDrawable;
  28. import android.graphics.drawable.Drawable;
  29. import android.net.http.AndroidHttpClient;
  30. import android.os.AsyncTask;
  31. import android.util.DisplayMetrics;
  32.  
  33. import android.widget.ImageView;
  34.  
  35. public final class UrlImageViewHelper {
  36. private static final String LOGTAG = "UrlImageViewHelper";
  37. public static int copyStream(InputStream input, OutputStream output) throws IOException
  38. {
  39. byte[] stuff = new byte[1024];
  40. int read = 0;
  41. int total = 0;
  42. while ((read = input.read(stuff)) != -1)
  43. {
  44. output.write(stuff, 0, read);
  45. total += read;
  46. }
  47. return total;
  48. }
  49.  
  50. static Resources mResources;
  51. static DisplayMetrics mMetrics;
  52. private static void prepareResources(Context context) {
  53. if (mMetrics != null)
  54. return;
  55. mMetrics = new DisplayMetrics();
  56. Activity act = (Activity)context;
  57. act.getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
  58. AssetManager mgr = context.getAssets();
  59. mResources = new Resources(mgr, mMetrics, context.getResources().getConfiguration());
  60. }
  61.  
  62. private static BitmapDrawable loadDrawableFromStream(Context context, InputStream stream) {
  63. prepareResources(context);
  64. final Bitmap bitmap = BitmapFactory.decodeStream(stream);
  65. //Log.i(LOGTAG, String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight()));
  66. return new BitmapDrawable(mResources, bitmap);
  67. }
  68.  
  69. public static final int CACHE_DURATION_INFINITE = Integer.MAX_VALUE;
  70. public static final int CACHE_DURATION_ONE_DAY = 1000 * 60 * 60 * 24;
  71. public static final int CACHE_DURATION_TWO_DAYS = CACHE_DURATION_ONE_DAY * 2;
  72. public static final int CACHE_DURATION_THREE_DAYS = CACHE_DURATION_ONE_DAY * 3;
  73. public static final int CACHE_DURATION_FOUR_DAYS = CACHE_DURATION_ONE_DAY * 4;
  74. public static final int CACHE_DURATION_FIVE_DAYS = CACHE_DURATION_ONE_DAY * 5;
  75. public static final int CACHE_DURATION_SIX_DAYS = CACHE_DURATION_ONE_DAY * 6;
  76. public static final int CACHE_DURATION_ONE_WEEK = CACHE_DURATION_ONE_DAY * 7;
  77.  
  78. public static void setUrlDrawable(final ImageView imageView, final String url, int defaultResource) {
  79. setUrlDrawable(imageView.getContext(), imageView, url, defaultResource, CACHE_DURATION_THREE_DAYS);
  80. }
  81.  
  82. public static void setUrlDrawable(final ImageView imageView, final String url) {
  83. setUrlDrawable(imageView.getContext(), imageView, url, null, CACHE_DURATION_THREE_DAYS);
  84. }
  85.  
  86. public static void loadUrlDrawable(final Context context, final String url) {
  87. setUrlDrawable(context, null, url, null, CACHE_DURATION_THREE_DAYS);
  88. }
  89.  
  90. public static void setUrlDrawable(final ImageView imageView, final String url, Drawable defaultDrawable) {
  91. setUrlDrawable(imageView.getContext(), imageView, url, defaultDrawable, CACHE_DURATION_ONE_DAY);
  92. }
  93.  
  94. public static void setUrlDrawable(final ImageView imageView, final String url, int defaultResource, long cacheDurationMs) {
  95. setUrlDrawable(imageView.getContext(), imageView, url, defaultResource, cacheDurationMs);
  96. }
  97.  
  98. public static void loadUrlDrawable(final Context context, final String url, long cacheDurationMs) {
  99. setUrlDrawable(context, null, url, null, cacheDurationMs);
  100. }
  101.  
  102. public static void setUrlDrawable(final ImageView imageView, final String url, Drawable defaultDrawable, long cacheDurationMs) {
  103. setUrlDrawable(imageView.getContext(), imageView, url, defaultDrawable, cacheDurationMs);
  104. }
  105.  
  106. private static void setUrlDrawable(final Context context, final ImageView imageView, final String url, int defaultResource, long cacheDurationMs) {
  107. Drawable d = null;
  108. if (defaultResource != 0)
  109. d = imageView.getResources().getDrawable(defaultResource);
  110. setUrlDrawable(context, imageView, url, d, cacheDurationMs);
  111. }
  112.  
  113. private static boolean isNullOrEmpty(CharSequence s) {
  114. return (s == null || s.equals("") || s.equals("null") || s.equals("NULL"));
  115. }
  116.  
  117. private static boolean mHasCleaned = false;
  118.  
  119. public static String getFilenameForUrl(String url) {
  120. return "" + url.hashCode() + ".urlimage";
  121. }
  122.  
  123. private static void cleanup(Context context) {
  124. if (mHasCleaned)
  125. return;
  126. mHasCleaned = true;
  127. try {
  128. // purge any *.urlimage files over a week old
  129. String[] files = context.getFilesDir().list();
  130. if (files == null)
  131. return;
  132. for (String file : files) {
  133. if (!file.endsWith(".urlimage"))
  134. continue;
  135.  
  136. File f = new File(context.getFilesDir().getAbsolutePath() + '/' + file);
  137. if (System.currentTimeMillis() > f.lastModified() + CACHE_DURATION_ONE_WEEK)
  138. f.delete();
  139. }
  140. }
  141. catch (Exception e) {
  142. e.printStackTrace();
  143. }
  144. }
  145.  
  146. private static void setUrlDrawable(final Context context, final ImageView imageView, final String url, final Drawable defaultDrawable, long cacheDurationMs) {
  147. cleanup(context);
  148. // disassociate this ImageView from any pending downloads
  149. if (imageView != null)
  150. mPendingViews.remove(imageView);
  151.  
  152. if (isNullOrEmpty(url)) {
  153. if (imageView != null)
  154. imageView.setImageDrawable(defaultDrawable);
  155. return;
  156. }
  157.  
  158. final UrlImageCache cache = UrlImageCache.getInstance();
  159. Drawable d = cache.get(url);
  160. if (d != null) {
  161. //Log.i(LOGTAG, "Cache hit on: " + url);
  162. if (imageView != null)
  163. imageView.setImageDrawable(d);
  164. return;
  165. }
  166.  
  167. final String filename = getFilenameForUrl(url);
  168.  
  169. File file = context.getFileStreamPath(filename);
  170. if (file.exists()) {
  171. try {
  172. if (cacheDurationMs == CACHE_DURATION_INFINITE || System.currentTimeMillis() < file.lastModified() + cacheDurationMs) {
  173. //Log.i(LOGTAG, "File Cache hit on: " + url + ". " + (System.currentTimeMillis() - file.lastModified()) + "ms old.");
  174. FileInputStream fis = context.openFileInput(filename);
  175. BitmapDrawable drawable = loadDrawableFromStream(context, fis);
  176. fis.close();
  177. if (imageView != null)
  178. imageView.setImageDrawable(drawable);
  179. cache.put(url, drawable);
  180. return;
  181. }
  182. else {
  183. //Log.i(LOGTAG, "File cache has expired. Refreshing.");
  184. }
  185. }
  186. catch (Exception ex) {
  187. }
  188. }
  189.  
  190. // null it while it is downloading
  191. if (imageView != null)
  192. imageView.setImageDrawable(defaultDrawable);
  193.  
  194. // since listviews reuse their views, we need to
  195. // take note of which url this view is waiting for.
  196. // This may change rapidly as the list scrolls or is filtered, etc.
  197. //Log.i(LOGTAG, "Waiting for " + url);
  198. if (imageView != null)
  199. mPendingViews.put(imageView, url);
  200.  
  201. ArrayList<ImageView> currentDownload = mPendingDownloads.get(url);
  202. if (currentDownload != null) {
  203. // Also, multiple vies may be waiting for this url.
  204. // So, let's maintain a list of these views.
  205. // When the url is downloaded, it sets the imagedrawable for
  206. // every view in the list. It needs to also validate that
  207. // the imageview is still waiting for this url.
  208. if (imageView != null)
  209. currentDownload.add(imageView);
  210. return;
  211. }
  212.  
  213. final ArrayList<ImageView> downloads = new ArrayList<ImageView>();
  214. if (imageView != null)
  215. downloads.add(imageView);
  216. mPendingDownloads.put(url, downloads);
  217.  
  218. AsyncTask<Void, Void, Drawable> downloader = new AsyncTask<Void, Void, Drawable>() {
  219.  
  220.  
  221.  
  222. @Override
  223. protected Drawable doInBackground(Void... params) {
  224. AndroidHttpClient client = AndroidHttpClient.newInstance(context.getPackageName());
  225. try {
  226. HttpGet get = new HttpGet(url);
  227. final HttpParams httpParams = new BasicHttpParams();
  228. HttpClientParams.setRedirecting(httpParams, true);
  229. get.setParams(httpParams);
  230. HttpResponse resp = client.execute(get);
  231. int status = resp.getStatusLine().getStatusCode();
  232. if(status != HttpURLConnection.HTTP_OK){
  233. // Log.i(LOGTAG, "Couldn't download image from Server: " + url + " Reason: " + resp.getStatusLine().getReasonPhrase() + " / " + status);
  234. return null;
  235. }
  236. HttpEntity entity = resp.getEntity();
  237. // Log.i(LOGTAG, url + " Image Content Length: " + entity.getContentLength());
  238. InputStream is = entity.getContent();
  239. FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
  240. copyStream(is, fos);
  241. fos.close();
  242. is.close();
  243. FileInputStream fis = context.openFileInput(filename);
  244. return loadDrawableFromStream(context, fis);
  245. }
  246. catch (Exception ex) {
  247. // Log.e(LOGTAG, "Exception during Image download of " + url, ex);
  248. return null;
  249. }
  250. finally {
  251. client.close();
  252. }
  253. }
  254.  
  255.  
  256. @Override
  257. protected void onPostExecute(Drawable result) {
  258. if (result == null)
  259. result = defaultDrawable;
  260. mPendingDownloads.remove(url);
  261. cache.put(url, result);
  262. for (ImageView iv: downloads) {
  263. // validate the url it is waiting for
  264. String pendingUrl = mPendingViews.get(iv);
  265. if (!url.equals(pendingUrl)) {
  266. //Log.i(LOGTAG, "Ignoring out of date request to update view for " + url);
  267. continue;
  268. }
  269. mPendingViews.remove(iv);
  270. if (result != null) {
  271. final Drawable newImage = result;
  272.  
  273. Drawable newSize=resize(newImage);
  274.  
  275.  
  276. final ImageView imageView = iv;
  277.  
  278. imageView.setImageDrawable(newSize);
  279. }
  280. }
  281. }
  282.  
  283. private BitmapDrawable resize(Drawable newImage) {
  284. // TODO Auto-generated method stub
  285.  
  286. Bitmap d = ((BitmapDrawable)newImage).getBitmap();
  287. Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 75, 75, false);
  288. return new BitmapDrawable(bitmapOrig);
  289. }
  290. };
  291. downloader.execute();
  292. }
  293.  
  294.  
  295.  
  296. private static Hashtable<ImageView, String> mPendingViews = new Hashtable<ImageView, String>();
  297. private static Hashtable<String, ArrayList<ImageView>> mPendingDownloads = new Hashtable<String, ArrayList<ImageView>>();
  298. }
Add Comment
Please, Sign In to add comment