这是一个通过URL获取网络图片的例子

1 package com.dasouViewer; 2 3 import java.io.InputStream; 4 import java.net.URL; 5 6 import javax.net.ssl.HttpsURLConnection; 7 8 import android.app.Activity; 9 import android.graphics.Bitmap; 10 import android.graphics.BitmapFactory; 11 import android.os.Bundle; 12 import android.os.Handler; 13 import android.os.Message; 14 import android.text.TextUtils; 15 import android.view.View; 16 import android.widget.EditText; 17 import android.widget.ImageView; 18 import android.widget.Toast; 19 20 public class MainActivity extends Activity { 21 protected static final int CHANGE_UI=1; 22 protected static final int ERROR=2; 23 private ImageView iv; 24 private EditText et_path; 25 /* 26 * 消息机制使用的3个步骤 27 * 1、子线程利用handler发送一条消息,该消息被放在主线程的消息队列里 28 * 2、主线程里面有一个looper消息轮询器 29 * 3、如果looper发现了新消息,则调用HandleMessage的方法进行处理 30 */ 31 32 33 //主线程创建消息处理器 34 private Handler handler=new Handler(){ 35 public void handleMessage(Message msg) { 36 if(msg.what==CHANGE_UI){ 37 Bitmap bitmap=(Bitmap)msg.obj; 38 iv.setImageBitmap(bitmap); 39 }else if(msg.what==ERROR){ 40 Toast.makeText(MainActivity.this, "加载图片失败", 0).show(); 41 42 } 43 }; 44 }; 45 @Override 46 protected void onCreate(Bundle savedInstanceState) { 47 super.onCreate(savedInstanceState); 48 setContentView(R.layout.activity_main); 49 iv=(ImageView)findViewById(R.id.iv); 50 et_path=(EditText)findViewById(R.id.et_path); 51 } 52 public void click(View view) { 53 final String path=et_path.getText().toString().trim(); 54 if(TextUtils.isEmpty(path)){ 55 Toast.makeText(this, "图片路径不能为空", 0).show(); 56 }else{ 57 new Thread(){ 58 public void run(){ 59 //进行加载操作 60 try { 61 //添加路径 62 URL url=new URL(path); 63 //根据url发送一个http请求 64 HttpsURLConnection conn=(HttpsURLConnection)url.openConnection(); 65 //设置请求方式 66 conn.setRequestMethod("GET"); 67 //设置加载超时时间 68 conn.setConnectTimeout(5000); 69 //伪装为IE浏览器 70 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"); 71 //获取服务器的返回码 72 int coad=conn.getResponseCode(); 73 //判断返回码 74 if(coad==200){ 75 //获取服务器端返回的数据流 76 InputStream is=conn.getInputStream(); 77 //把数据流转换成位图 78 Bitmap bitmap=BitmapFactory.decodeStream(is); 79 //只有主线程才能进行更改UI的操作,发现子线程更改立刻挂掉(所以需要借助消息机制) 80 //iv.setImageBitmap(bitmap); 81 //告诉主线程一个消息,让其帮忙修改Ui 82 Message msg=new Message(); 83 msg.obj=bitmap; 84 msg.what=CHANGE_UI; 85 handler.sendMessage(msg); 86 87 }else{ 88 //子线程的UI操作,错误 89 //Toast.makeText(MainActivity.this, "服务器加载失败",0).show(); 90 Message msg=new Message(); 91 msg.what=ERROR; 92 handler.sendMessage(msg); 93 } 94 95 } catch (Exception e) { 96 // TODO Auto-generated catch block 97 e.printStackTrace(); 98 //此处也是一个在子线程中更新UI的操作,同样报错 99 //Toast.makeText(MainActivity.this, "图片加载失败", 0).show(); 100 Message msg=new Message(); 101 msg.what=ERROR; 102 handler.sendMessage(msg); 103 104 } 105 } 106 }.start(); 107 108 109 110 } 111 112 } 113 114 115 116 }
该项目的二个步骤:
1、获取网络服务 2、修改UI的操作不能子线程中进行,引入消息机制进行子主线程之间的数据传递。