MainActivity中的代码:
public EditText etUrl;
public ImageView picture;
public static final int SHOW_IMAGE=0;
private Handler handler=new Handler(){
public void handlerMessage(android.os.Message msg){
switch(msg.what){
case SHOW_IMAGE:
Bitmap bitmap=(Bitmap)msg.obj;
picture.setImageBitmap(bitmap);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findView();
}
public void findView(){
etUrl=(EditText)findViewById(R.id.editText1);
picture=(ImageView)findViewById(R.id.imageView1);
}
public void showImage(View view){//某button的onClick属性是此方法
//final String path=etUrl.getText().toString();
final String path="http://pic.sogou.com/d?query=%B0%D9%B6%C8%CD%BC%C6%AC%B4%F3%C8%AB&mood=0&picformat=0&mode=1&di=0&p=26050500&dp=1&did=5#did4";
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_SHORT).show();
}
else{
new Thread(){
public void run(){
try{
URL url=new URL(path);//创建地址
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();//打开连接
httpURLConnection.setRequestMethod("GET");//设置请求方式
httpURLConnection.setConnectTimeout(5000);//设置超时时间
int responseCode=httpURLConnection.getResponseCode();
if(responseCode==200){//正确连接上网络时
InputStream is=httpURLConnection.getInputStream();//创建网络输入流
Bitmap bitmap=BitmapFactory.decodeStream(is);
Message msg=new Message();
msg.what=SHOW_IMAGE;
msg.obj=bitmap;
handler.sendMessage(msg);//将msg转发给主线程中的handlerMessage管理,多线程中主线程以外的线程不能操控主布局文件中的控件。
}
else{
Toast.makeText(MainActivity.this, "图片显示失败", Toast.LENGTH_SHORT).show();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}.start();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}