阿冰教你一步一步做Android新闻客户端(二)两种异步线程加载图片的方法
哈哈哈抱着没人看的心态随便写,直接上代码,各位看官看注释
一种Thread 一种AsyncTask 先不说用框架
public class ImageLoader { private ImageView mImageView; private String mUrl;
//Thread明显很low 还需要handler来传递消息,好累T T
android.os.Handler mHandler = new android.os.Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mImageView.getTag().equals(mUrl)) mImageView.setImageBitmap((Bitmap)msg.obj); } }; public void showImageByThread(ImageView imageView, final String url) { mImageView =imageView; mUrl = url;//对传过来的imageView 和url进行映射下 映射成mImageView 和mUrl 哈哈 这样就可以使用咯(还为了避免程序逻辑顺序错误,和viewholder的机制差不多) new Thread() { @Override public void run() { super.run(); Bitmap bitmap = getBitmapFromURL(url); Message message = Message.obtain(); message.obj = bitmap; mHandler.sendMessage(message); } }.start(); } //创建从URL获取Bitmap的放方法,还是老一套 很多try/catch 看着就心累,这么多就为了获取Bitmap public Bitmap getBitmapFromURL(String stringUrl) { Bitmap bitmap; BufferedInputStream bis = null; URL url1 = null; try { url1 = new URL(stringUrl); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url1.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { bis = new BufferedInputStream(connection.getInputStream()); bitmap = BitmapFactory.decodeStream(bis); connection.disconnect(); return bitmap; } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } }return null; }
//========================================================我是无耻的分割线========请无视我==============下面是AsyncTask获取网络图片=================================================高能警报======================
public void showImageByAsyncTask (ImageView imageView,final String mUrl){ new MyIconSyncTask(imageView,mUrl).execute(mUrl); }
//三个参数传进来的String url ,过程返回值不要写Void , 结果返回值 Bitmap class MyIconSyncTask extends AsyncTask<String,Void,Bitmap> { private ImageView mImageView; private String mUrl; public MyIconSyncTask(ImageView imageView,String url){ //写个构造方法是为了映射下得到的Imageview 和String url mUrl = url; mImageView = imageView; } @Override protected Bitmap doInBackground(String... params) { return getBitmapFromURL(params[0]); //把耗时操作交给doInBackground } @Override protected void onPostExecute(Bitmap bitmap) { //通过onPostExecute和UI线程交互 完全不用handler 妈妈再也不用担心我用handler了 ,再这个方法里imageview设置bitmap super.onPostExecute(bitmap); if (mImageView.getTag().equals(mUrl)) { mImageView.setImageBitmap(bitmap); } } } }