使用HttpURLConnection加载网络图片
2018-03-13 21:24
441 查看
**使用HttpURLConnection加载网络图片**
**代码注意点:
1、加载网络图片需要用到Bitmap
2、加载网络图片有时候比较耗时,可以用Handler或AsyncTask来解决
代码展示(AsyncTask)**
1.
//在xml文件中 <Button android:id="@+id/main_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="加载图片"/> <ImageView android:id="@+id/main_image" android:layout_width="match_parent" android:layout_height="match_parent" />
2.//在Activity中
public class MainActivity extends AppCompatActivity { private Button downBtn; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindID(); downBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImgLoadTask imgLoadTask=new ImgLoadTask(imageView); imgLoadTask.execute("http://p2.so.qhimgs1.com/bdr/_240_/t01b20aa81f9cd5a5f2.jpg");//execute里面是图片的地址 } }); } private void bindID() { downBtn=findViewById(R.id.main_btn); imageView=findViewById(R.id.main_image); } } 3.` //在ImgLoadTask.java中 public class ImgLoadTask extends AsyncTask<String,Integer,Bitmap>{ private ImageView imageView; //为什么要加一个构造方法--有传值的需求 public ImgLoadTask(ImageView imageView){ this.imageView=imageView; } @Override protected Bitmap doInBackground(String... strings) { //加载网络图片,最后获取到一个Bitmap对象,返回Bitmap对象 Bitmap bm=null; try { //创建URL对象 URL url=new URL(strings[0]); //通过URL对象得到HttpURLConnection HttpURLConnection connection= (HttpURLConnection) url.openConnection();(//这边需要强制转换) //得到输入流 InputStream inputStream=connection.getInputStream(); //把输入流转换成Bitmap类型对象 bm= BitmapFactory.decodeStream(inputStream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bm; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); imageView.setImageBitmap(bitmap); }
相关文章推荐
- 使用HttpURLConnection访问网络——加载网络图片
- 使用HttpURLConnection从网络中下载图片
- 使用HttpURLConnection加载图片
- Android - HttpURLConnection下载网络文件,加载网络图片
- 【黑马Android】(05)短信/查询和添加/内容观察者使用/子线程网络图片查看器和Handler消息处理器/html查看器/使用HttpURLConnection采用Post方式请求数据/开源项目
- 使用HttpURLConnection和AsyncTask从网络缓存图片
- 0314-使用HttpURLConnection下载网络图片并显示
- HttpURLConnection加载网络图片
- 用HttpUrlConnection来加载网络图片
- 使用HttpURLConnection下载网络图片
- 关于HttpUrlConnection加载和下载网络图片的学习
- Http访问网络(AsyncTask 异步加载和使用HttpURLConnection)
- 使用HttpURLConnection下载网络图片并显示
- 使用HttpURLconnection从网络获取图片
- Android使用HttpURLConnection显示网络图片
- Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)
- Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)
- 代理网络环境下使用HttpURLConnection
- 简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源
- HttpURLConnection下载网络图片