Android中子线程网络查看器与Handler消息处理器

xml文件代码部分

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><ImageViewandroid:id="@+id/image"android:layout_width="fill_parent"android:layout_height="0dip"android:layout_weight="1"/><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><EditTextandroid:id="@+id/edit"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:singleLine="true"android:text="http://e.hiphotos.baidu.com/image/pic/item/d52a2834349b033b6764dedb17ce36d3d439bdc6.jpg"/><Buttonandroid:id="@+id/go"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Go"android:textSize="20sp"/></LinearLayout></LinearLayout>

Activity

packagecom.example.android01;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;importandroid.app.Activity;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.ImageView;importandroid.widget.Toast;publicclassMainActivityextendsActivityimplementsOnClickListener{privateImageViewimage;privateEditTextedit;privateButtonbut;privatefinalintsuccess=0;privateHandlerhandler=newHandler(){@OverridepublicvoidhandleMessage(android.os.Messagemsg){Bitmapb=(Bitmap)msg.obj;if(b!=null){if(msg.what==success){image.setImageBitmap(b);}}else{Toast.makeText(getApplicationContext(),"获取图片错误",0).show();}};};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);image=(ImageView)findViewById(R.id.image);edit=(EditText)findViewById(R.id.edit);but=(Button)findViewById(R.id.go);but.setOnClickListener(this);}@OverridepublicvoidonClick(Viewv){finalStringurl=edit.getText().toString();newThread(newRunnable(){@Overridepublicvoidrun(){Bitmapbit=getImageFromNet(url);//image.setImageBitmap(bit);Messagemsg=newMessage();msg.obj=bit;msg.what=success;handler.sendMessage(msg);}}).start();}privateBitmapgetImageFromNet(Stringurl){HttpURLConnectionconn=null;try{URLmURL=newURL(url);//创建一个URL连接conn=(HttpURLConnection)mURL.openConnection();//得到一个connection对象conn.setRequestMethod("GET");//设置请求方法为GETconn.setConnectTimeout(10000);//设置连接超时时间conn.setReadTimeout(5000);//设置读取过程中的异常conn.connect();intresponseCode=conn.getResponseCode();//获取响应码,404,500,200if(responseCode==200){//访问成功InputStreamin=conn.getInputStream();Bitmapbitmap=BitmapFactory.decodeStream(in);//将从服务器获取的流变成Bitmap位图returnbitmap;}else{Toast.makeText(this,"获取图片失败",0).show();}}catch(Exceptione){e.printStackTrace();}finally{if(conn!=null){conn.disconnect();}}returnnull;}}