public class MainActivity extends AppCompatActivity {
private Button bt_load;
private ImageView ivIcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_load = (Button) findViewById(R.id.bt_load);
ivIcon = (ImageView) findViewById(R.id.ivIcon);
bt_load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getInfo("http://p1.qq181.com/cms/120503/2012050320291269450.jpg");
}
});
}
private void getInfo(String s) {
new AsyncTask() {
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap!=null){
ivIcon.setImageBitmap(bitmap);
}else{
ivIcon.setImageResource(R.mipmap.ic_launcher);
}
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url=new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int code = connection.getResponseCode();
if (code==200){
InputStream is = connection.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(s);
}