public class MainActivity
extends AppCompatActivity {
private Button
button;
private ImageView
iv;
private ProgressBar
pb;
private Bitmap
bm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main);
button = (Button) findViewById(R.id.
button);
iv = (ImageView)findViewById(R.id.
iv);
pb = (ProgressBar) findViewById(R.id.
pb);
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
datas();
}
});
}
private void datas() {
//(第一个)(第二个)(第三个)
AsyncTask<Void, Void, Bitmap> asyncTask =
new AsyncTask<Void, Void, Bitmap>(){
//asyncTask参数是对象 可以用Void来代替
//第二个参数类似于进度条的作用
//在子线程开启之前启动方法
@Override
protected void onPreExecute() {
//显示
pb.setVisibility(View.
VISIBLE);
iv.setImageBitmap(
bm);
}
//这方法在子线程开启之前启动
//重要:在子线程doInBackground中获取信息并在onPreExecute中去显示
@Override
protected Bitmap doInBackground(Void... voids) {
//第一个Void对应的Void//网络请求
String path =
"https://img-my.csdn.net/uploads/201407/26/1406383059_8814.jpg";
try {
URL url =
new URL(path);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setConnectTimeout(
2000);
uc.setReadTimeout(
2000);
// uc.setRequestMethod("GET");
int code = uc.getResponseCode();
if(code==
200){
InputStream is = uc.getInputStream();
//用BitmapFactory得到流
bm = BitmapFactory.
decodeStream(is);
return bm;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
//在此方法中运行主线程
@Override
protected void onPostExecute(Bitmap bitmap) {
//第三个参数
iv.setImageBitmap(bitmap);
}
};
asyncTask.execute();
}
}