利用HTTP从网络下载图片并显示
利用Http从指定地址下载图片并显示出来
创新互联专注于企业全网整合营销推广、网站重做改版、浪卡子网站定制设计、自适应品牌网站建设、HTML5建站、商城网站建设、集团公司官网建设、外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为浪卡子等各大城市提供网站开发制作服务。
/** * 简单的封装一个http下载类 * */ public class HttpUtils { //指定一张图片 private String URL_PATH = "http://img.wangxiao.cn/files/RemoteFiles/20140420/095185001.jpg"; public HttpUtils(){ } //返回一个byte类型的数组 public byte[] getData(){ HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(URL_PATH); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { byte[] data = EntityUtils.toByteArray(httpResponse .getEntity()); return data; } } catch (Exception e) { e.printStackTrace(); } return null; } }
//用于调用的avtivity public class MainActivity extends Activity { private Button btnDown; private ImageView img; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnDown = (Button) findViewById(R.id.button1); img = (ImageView) findViewById(R.id.p_w_picpathView1); dialog = new ProgressDialog(this); dialog.setTitle("提示信息"); dialog.setMessage("正在下载中,请稍后..."); dialog.setCancelable(false); btnDown.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(mRunnable).start(); dialog.show(); } }); } private Runnable mRunnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub byte[] data = new HttpUtils().getData(); Message msg = Message.obtain(); msg.obj = data; msg.what = 0x001; handler.sendMessage(msg); } }; private Handler handler = new Handler() { // 在Handler中获取消息,重写handleMessage()方法 @Override public void handleMessage(Message msg) { // 判断消息码是否为0x001 if(msg.what == 0x001){ byte[] data=(byte[])msg.obj; Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length); img.setImageBitmap(bmp); dialog.dismiss(); } } }; }
//布局 .xml 很简单只有两个控件
//最后manifest中别忘了 网络权限
当前标题:利用HTTP从网络下载图片并显示
浏览地址:http://ybzwz.com/article/ggschi.html