下面的代码是下载一个网络上的图片
1、直接贴上代码:
public class MainActivity extends Activity {
private ImageView imageview;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView)findViewById(R.id.imageview);
//将下载的图片更新到UI
handler = new Handler(){
public void handleMessage(Message message){
Bitmap bitmap = (Bitmap) message.obj;
imageview.setImageBitmap(bitmap);
}
};
//下载图片
new Thread(downloadRun).start();
}
/*
* 访问网络不能在主程序中进行,所以用Runnable()
*/
Runnable downloadRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
downloadPicture();
}
};
private void downloadPicture(){
String urlStr = "https://img-my.csdn.net/uploads/201407/26/1406383291_6518.jpg";
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);//设置网络连接超时
conn.setReadTimeout(10 * 1000);//设置读取数据超时
conn.setDoInput(true);//设置是否从httpUrlConnection读入,默认情况下是true;
/*
*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
*http正文内,因此需要设为true, 默认情况下是false;
*/
conn.setDoOutput(true);
InputStream in = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(in);
/* 1、android子线程不能更新主线程创建的组件解决方法
*
* 2、如果强制使用 imageview.setImageBitmap(bitmap);
* 则会报错 android.view.ViewRootImpl$CalledFromWrongThreadException
*/
Message message = Message.obtain();
message.obj = bm;
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
2、运行结果如下:
3、刚开始在编写该Demo时,会出现以下两个报错:
java.lang.RuntimeException: Unable to start activity ComponentInfo {com.example.demo/com.example.demo.MainActivity}: android.os.NetworkOnMainThreadException
此异常的主要原因是访问网络时不能在主线程中进行。
参考资料:http://geeksun.iteye.com/blog/1447708
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
此异常主要原因是android子线程不能更新主线程中的UI
参考资料:http://zhuyifeng.iteye.com/blog/1571373
完整代码下载:http://download.csdn.net/download/yegucheng2618/7849735