从网络中下载图片并进行显示

通过get请求方式获取网络图片----主要是方便以后查阅以及做一个笔记

任务要求:

1.新建一个布局文件,在布局文件中添加Button、ImageView两个控件

2.新建一个GetPictThread实现Runnable接口

  (1)定义一个handler用于将数据传送到主线程中

  (2)定义一个有参方法,参数包含path还有handler

  (3)在run()方法中完成网络图片的获取(子线程)

3.在MainActivity中完成图片显示(即主线程)

 

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取网络图片"/>

    <ImageView
        android:id="@+id/image_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        />

</LinearLayout>

 

 

java代码:

package com.example.jiaho.handleproject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class ImageDownLoadActivity extends AppCompatActivity implements View.OnClickListener{

    public static final int DOWNLOAD_CODE = 10001;
    public static final int DOWNLOAD_FAIL = 300;
    public static final int CONNECT_TIMEOUT = 2000;
    private ImageView image_download;
    private Button btn_download;

    private Handler handler;

    private String path="https://img2.mukewang.com/5adfee7f0001cbb906000338-240-135.jpg";

    private int fileLength;

    private Bitmap mBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_download);

        //初始化控件
        initialView();

        btn_download.setOnClickListener(this);

        //接收子线程的消息
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case DOWNLOAD_CODE:
                        /*
                        * 更新UI
                        * 提取消息中的bitmap,并设置ImageView
                        * */
                        Bitmap bitmap=(Bitmap) msg.obj;
                        if (bitmap!=null){
                            image_download.setImageBitmap(bitmap);//disPlay image
                        }
                        break;
                    case DOWNLOAD_FAIL:
                        Toast.makeText(ImageDownLoadActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

    }

    //初始化控件
    public void initialView(){
        btn_download=findViewById(R.id.btn_download);
        image_download=findViewById(R.id.image_download);
    }

    //按钮点击
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_download:
                //开启线程
                new Thread(new GetPictThread(handler,path)).start();
                break;
        }
    }


    //自定义GetPictThread类实现Runnable类
    public class GetPictThread implements Runnable{
        //定义handler和path
        public Handler handler;
        public String path;

        //带参构造
        public GetPictThread(Handler handler, String path) {
            this.handler = handler;
            this.path = path;
        }

        //在run方法中实现图片下载
        @Override
        public void run() {
            //通过Get方法请求获取网络图片
            try {
                URL url=new URL(path);
                HttpURLConnection connection=(HttpURLConnection) url.openConnection();

                //设置请求方式
                connection.setRequestMethod("GET");
                //设置超时时间
                connection.setConnectTimeout(30*1000);
                //发起连接
                connection.connect();

                //获取状态码
                int requestCode=connection.getResponseCode();
                System.out.println(requestCode);

                if (requestCode==HttpURLConnection.HTTP_OK){
                    /*
                    * 1.获得文件长度
                    * 2.通过缓冲输入流
                    * 3.将输入流转换成字节数组
                    * 4.将字节数组转换成位图
                    * */
                    fileLength=connection.getContentLength();

                    InputStream is=new BufferedInputStream(connection.getInputStream());

                    //获取到字节数组
                    byte[] arr=streamToArr(is);

                    //将字节数组转换成位图
                    mBitmap= BitmapFactory.decodeByteArray(arr,0,arr.length);

                    /*
                    * 下载完成后将消息发送出去
                    * 通知主线程,更新UI
                    * */
                    Message message=Message.obtain();
                    message.what=DOWNLOAD_CODE;
                    message.obj=mBitmap;
                    handler.sendMessage(message);

                }else {
                    Log.e("TAG", "run:error "+requestCode);
                }
            }catch (MalformedURLException e){
                e.printStackTrace();
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }catch (IOException e){
                e.printStackTrace();
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }
        }
    }

    //将输入流转换成字节数组
    public byte[] streamToArr(InputStream inputStream){

        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;

            while ((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }

            //关闭输出流
            baos.close();
            //关闭输入流
            inputStream.close();
            //返回字节数组
            return baos.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
            //若失败,则返回空
            return null;
        }
    }

}

 

 

必不可少的一步,给网络添加权限:

<uses-permission android:name="android.permission.INTERNET"/>

 

 

然后可以开始图片下载啦啦啦啦啦啦!

发布了55 篇原创文章 · 获赞 45 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览