1. 程式人生 > >從網路中下載圖片並進行顯示

從網路中下載圖片並進行顯示

通過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"/>

然後可以開始圖片下載啦啦啦啦啦啦!