public class MainActivity extends Activity {
protected static final int SUCCESS = 1;
private EditText et_id;
private ImageView img;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
Bitmap bm = (Bitmap) msg.obj;
img.setImageBitmap(bm);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_id = (EditText) findViewById(R.id.et_id);
img = (ImageView) findViewById(R.id.iv_show);
}
public void downs(View v) {
//handler+message
//只要是耗时操作,都开辟新的线程
new Thread() {
public void run() {
Bitmap bm = downimg();
Message msg = new Message();
msg.obj = bm;
msg.what = SUCCESS;
handler.sendMessage(msg);
};
}.start();
}
public Bitmap downimg() {
String path = et_id.getText().toString().trim();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
byte[] b = Utils.write(in);
Bitmap bm = BitmapFactory.decodeByteArray(b, 0, b.length);
return bm;
} else {
Toast.makeText(getApplicationContext(), "请求失败", 2000).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
public class Utils {
public static byte[] write(InputStream in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
try {
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
return out.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}