通过网络访问图片,并通过Handler更新主线程的控件。
public class MainActivity extends Activity {
protected static final String TAG = "MainActivity";
private Button btn_photo;
private ImageView iv_photo;
private EditText et_url;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG, " 消息 : " + msg);
if (msg.what == 0) {
iv_photo.setImageBitmap((Bitmap) msg.obj);
}else if (msg.what == 1) {
Toast.makeText(MainActivity.this, "抓取失败", 0).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_photo = (ImageView) findViewById(R.id.iv_photo);
et_url = (EditText) findViewById(R.id.et_photo);
btn_photo = (Button) findViewById(R.id.btn_go);
btn_photo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String uri = et_url.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = getImageFromNet(uri);
if (bitmap != null) {
Message msg = new Message();
msg.what = 0;
msg.obj = bitmap;
handler.sendMessage(msg);
}else if (bitmap == null) {
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}
}
}).start();
// iv_photo.setImageBitmap(bitmap);
}
});
}
private Bitmap getImageFromNet(String url){
HttpURLConnection conn = null;
try {
URL mURL = new URL(url); //创建一个URL对象
//创建一个http连接对象
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET"); //采用get的方法请求数据
conn.setConnectTimeout(10*1000); //设置10s的连接超时
conn.setReadTimeout(5*1000); //读取超时
conn.connect(); //开始连接
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
//访问成功
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}else {
Toast.makeText(this, "访问失败", 0).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//断开连接
conn.disconnect();
}
return null;
}
}