使用HttpURLConnection加载网络图片

         **使用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);

    }

版权声明:本文为R2Y2A_1113原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。