通过url地址,在通过handler将图片显示在ImageView上
public class MainActivity extends Activity {
private ImageView iv;
private myhandler handler=new myhandler(this);
private final int LOAD_SUCCESS=0;
/**
* 访问网络的操作必须在工作线程中完成
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView) findViewById(R.id.iv);
}
private class myhandler extends Handler{//防止内存溢出
private final WeakReference<MainActivity> activity;
public myhandler(MainActivity activitys) {
// TODO Auto-generated constructor stub
activity=new WeakReference<MainActivity>(activitys);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity2 = activity.get();
if(activity2!=null){
switch (msg.what) {
case LOAD_SUCCESS:
iv.setImageBitmap((Bitmap) msg.obj);
break;
}
}
}
}
private class myThrad implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://pic.sogou.com/d?query=%B3%C2%C7%C7%B6%F7&mood=0&picformat=0&mode=1&di=0&did=14#did13");
InputStream stream = url.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
Message message = handler.obtainMessage(LOAD_SUCCESS,bitmap);
handler.sendMessage(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
加访问网络额权限