ImageLoader.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.example.myapplication;
  2. import android.graphics.Bitmap;
  3. import android.graphics.BitmapFactory;
  4. import android.os.Handler;
  5. import android.os.Message;
  6. import android.widget.ImageView;
  7. import javax.net.ssl.HttpsURLConnection;
  8. import java.io.BufferedInputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.net.URL;
  12. public class ImageLoader {
  13. private ImageView mImageView;
  14. private String murl;
  15. private Handler handler = new Handler(){
  16. @Override
  17. public void handleMessage(Message msg) {
  18. super.handleMessage(msg);
  19. if(mImageView.getTag().equals(murl)) {
  20. mImageView.setImageBitmap((Bitmap) msg.obj);
  21. }
  22. }
  23. };
  24. public void showImagerByThread(ImageView imageView, final String url){
  25. mImageView = imageView;
  26. murl = url;
  27. new Thread(){
  28. @Override
  29. public void run() {
  30. super.run();
  31. Bitmap bitmap = getBitmapFromURL(url);
  32. Message message = Message.obtain();
  33. message.obj = bitmap;
  34. handler.sendMessage(message);
  35. }
  36. }.start();
  37. }
  38. public Bitmap getBitmapFromURL(String urlString){
  39. Bitmap bitmap;
  40. InputStream is = null;
  41. try {
  42. URL url = new URL(urlString);
  43. HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
  44. is = new BufferedInputStream(connection.getInputStream());
  45. bitmap = BitmapFactory.decodeStream(is);
  46. connection.disconnect();
  47. return bitmap;
  48. } catch (java.io.IOException e) {
  49. e.printStackTrace();
  50. } finally {
  51. try {
  52. is.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. return null;
  58. }
  59. }