setContentView(R.layout.activity_main);
btnPreview = (Button) findViewById(R.id.btnPreview);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editText);
btnPreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ","")); // 转换字符串
new MyDownloadTask().execute(); // 执行Http请求
while(!finishFlag) {} // 等待数据接收完毕
imageView.setImageBitmap(pngBM); // 显示图片
finishFlag = false; // 标识回位
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
}
class MyDownloadTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
//display progress dialog.
}
protected Void doInBackground(Void... params) {
try {
URL picUrl = Url; // 获取URL地址
HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
// conn.setConnectTimeout(1000); // 建立连接
// conn.setReadTimeout(1000);
conn.connect(); // 打开连接
if (conn.getResponseCode() == 200) { // 连接成功,返回数据
InputStream ins = conn.getInputStream(); // 将数据输入到数据流中
pngBM = BitmapFactory.decodeStream(picUrl.openStream()); // 解析数据流
finishFlag = true; // 数据传输完毕标识
ins.close(); // 关闭数据流
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// dismiss progress dialog and update ui
}