Android显示网络中的图片

来源:互联网 发布:数据分析的方法有哪些 编辑:程序博客网 时间:2024/06/05 06:35

Android显示网络中的图片

效果图:

代码:

private Handler handler=new Handler(){    public void handleMessage(android.os.Message msg){    switch (msg.what) {case 1:Bitmap bitmap=(Bitmap) msg.obj;ivName.setImageBitmap(bitmap);break;default:break;}    }    };    public void viewImage(View view){    final String path=etUrl.getText().toString();    if(TextUtils.isEmpty(path)){    Toast.makeText(this, "内容为空", Toast.LENGTH_LONG).show();    }else{    new Thread(){    public void run(){    try {URL url=new URL(path);HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("GET");httpURLConnection.setReadTimeout(5000);int op=httpURLConnection.getResponseCode();if(op==200){InputStream in=url.openStream();Bitmap bitmap=BitmapFactory.decodeStream(in);Message msg=new Message();msg.what=1;msg.obj=bitmap;handler.sendMessage(msg);}else{Toast.makeText(MainActivity.this, "获取失败", Toast.LENGTH_LONG).show();}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}    };        }.start();    }    }


 

0 0
原创粉丝点击