布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="从网络获取图片"
android:layout_marginLeft="120dp"
/>
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/button"
/>
</RelativeLayout>
活动代码:
public class MainActivity extends AppCompatActivity {
private String imageUrl = "http://news.sciencenet.cn/upload/news/images/2011/3/20113301123128272.jpg";
private Button button;
private ImageView img;
//在消息队列中实现对控件的更改
private Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
Bitmap bmp=(Bitmap)msg.obj;
img.setImageBitmap(bmp);
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
img = (ImageView) findViewById(R.id.img);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//新建线程加载图片信息,发送到消息队列中
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bmp = getURLimage(imageUrl);
Message msg = new Message();
msg.what = 0;
msg.obj = bmp;
handle.sendMessage(msg);
}
}).start();
}
});
}
private Bitmap getURLimage(String imageUrl) {
Bitmap bmp = null;
try {
URL myurl = new URL(imageUrl);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(6000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
}