在前面都写到用AsyncTask来获取网络中的图片。其实利用消息机制也能获取网络中的图片,而且本人感觉用消息机制还是挺简单的。
消息机制的图解:
& lt; FrameLayout xmlns: android=" http://schemas.android.com/apk/res/android " xmlns:工具=" http://schemas.android.com/tools " android: layout_width=" match_parent " android: layout_height=" match_parent " 工具:上下文=癱n.edu.huse.handle.MainActivity”比; & lt; ImageView android: layout_width=" match_parent " android: layout_height=" match_parent " android: id=癅 + id/iv_image”/比; & lt;按钮 android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: onClick=" getImage " android:文本="获取网络图片” android: layout_gravity="底部|中心” android: layout_marginBottom=" 20 dp/比; & lt;/FrameLayout> >之前
MainActivity。java
包cn.edu.huse.handle; 进口java.io.InputStream; 进口java.net.HttpURLConnection; 进口java.net.MalformedURLException; 进口java.net.URL; 进口android.app.Activity; 进口android.graphics.Bitmap; 进口android.graphics.BitmapFactory; 进口android.os.Bundle; 进口handler; 进口android.os.Message; 进口android.view.View; 进口android.widget.ImageView; 进口android.widget.Toast;/* * * @author联想 * */公开课MainActivity延伸活动{ 保护静态最终int LOAD_SUCCESS=0; 私有静态最终int LOAD_ERROR=1; 私人ImageView iv_image; 私人处理程序mHandler=new处理程序(){ 公共空间handleMessage(消息味精){ 开关(msg.what) { 案例LOAD_SUCCESS://加载图片成功 位图的位图=(位图)msg.obj;//获取消息里面的数据 iv_image.setImageBitmap(位图); 打破; 案例LOAD_ERROR://加载失败 Toast.makeText (MainActivity。这个,”图片加载失败”,0),告诉(); 打破; } }; }; @Override 保护无效alt=" android利用消息机制获取网络图片”>
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
android利用消息机制获取网络图片