如何用安卓中异步从网上获取图片内容

来源:互联网 发布:windows 文件共享 编辑:程序博客网 时间:2024/06/05 05:38




有时候我们做项目或者弄点什么的时候需要在网络上获取图片



那么我们应该先写一个类  自定义的类  然后调用


package com.example.message5_16;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.widget.ImageView;import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.net.HttpURLConnection;import java.net.URL;/** * Created by xue on 2017/5/9. */public class My extends AsyncTask<String,Integer,byte[]> {    private ImageView img;    private ProgressDialog pd;    public My(ImageView img, ProgressDialog pd)    {        this.img = img;        this.pd = pd;    }    @Override    protected void onPreExecute() {        super.onPreExecute();        pd.show();    }    @Override    protected void onProgressUpdate(Integer... values) {        super.onProgressUpdate(values); // 更新进度        pd.setProgress(values[0]);    }    @Override    protected byte[] doInBackground(String... params) {        URL url = null;        HttpURLConnection huc = null;        BufferedInputStream bis = null;        ByteArrayOutputStream bos = null;        byte[] bArray = null;        try {            url = new URL(params[0]);            huc = (HttpURLConnection) url.openConnection();            huc.connect();            if (huc.getResponseCode() == 200)            {                int temp = huc.getContentLength();//总大小                bis = new BufferedInputStream(huc.getInputStream());                bos = new ByteArrayOutputStream();                byte[] b = new byte[1024];                int sum = 0;                int length = 0;                while ((length = bis.read(b)) != -1)                {                    bos.write(b,0,length);                    bos.flush();                    sum += length;                   publishProgress(sum*100/temp);                }                bArray = bos.toByteArray();                return bArray;            }        } catch (Exception e) {            e.printStackTrace();        }finally {            if (bis != null)            {                try {                    bis.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (bos != null)            {                try {                    bos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            huc.disconnect();        }        return null;    }    @Override    protected void onPostExecute(byte[] bytes) {        super.onPostExecute(bytes);        if (bytes != null && img != null)        {            Bitmap bm = BitmapFactory.decodeByteArray(bytes,0,bytes.length);            img.setImageBitmap(bm);            pd.dismiss();        }    }}




然后在我们的JAVA主页面中调用



package com.example.message5_16;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity {    private ImageView imageView;    private ProgressDialog dialog;    private Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg != null)            {                int what = msg.what;                switch (what){                    case 100:                        int arg1 = msg.arg1;                        dialog.setProgress(arg1);                        break;                    case 200:                        dialog.dismiss();                        Bitmap obj = (Bitmap) msg.obj;                        imageView.setImageBitmap(obj);                        break;                }            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        imageView = (ImageView) this.findViewById(R.id.img);        dialog = new ProgressDialog(this);        dialog.setTitle("进度条对话框");        dialog.setMessage("正在加载中.............");        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        dialog.setIcon(getResources().getDrawable(R.mipmap.ic_launcher));       // dialog.setMax(100);    }    public void onClick(View view){        dialog.show();        new Thread()        {            @Override            public void run() {                super.run();                try {                    Thread.sleep(200);                } catch (InterruptedException e) {                    e.printStackTrace();                }                URL url = null;                HttpURLConnection huc = null;                Bitmap bitmap = null;                BufferedInputStream bis = null;                ByteArrayOutputStream bos = null;                try {                    url = new URL("http://i01.pictn.sogoucdn.com/16e0e03aa1b7d3d8");//图片路径                    huc = (HttpURLConnection) url.openConnection();                    huc.setRequestMethod("GET");                    huc.connect();                    if (huc.getResponseCode() == 200)                    {                        int toat = huc.getContentLength();                        bis = new BufferedInputStream(huc.getInputStream());                        bos = new ByteArrayOutputStream();                        byte[] bytes = new byte[1024];                        int len = 0;                        int sum = 0;                        while ((len = bis.read(bytes)) != -1)                        {                            sum += len;                            bos.write(bytes,0,len);                            bos.flush();                            Message m = Message.obtain();                            m.arg1 = sum*100/toat;                            m.what = 100;                            handler.sendMessage(m);                        }                        byte[] bArray = bos.toByteArray();                        bitmap = BitmapFactory.decodeByteArray(bArray,0,bArray.length);                    }                } catch (Exception e) {                    e.printStackTrace();                } finally {                    huc.disconnect();                }                Message obtain = Message.obtain();                obtain.obj = bitmap;                obtain.what = 200;                handler.sendMessage(obtain);            }        }.start();    }}



XML文件中直接给一个按钮加一个ImageView控件就好了


例如:


<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent" android:layout_height="match_parent"    tools:context="com.example.message5_16.MainActivity">    <Button        android:id="@+id/button"        android:hint="点击获取图片"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"/>    <ImageView        android:id="@+id/img"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_below="@id/button"        android:src="@mipmap/ic_launcher"/></RelativeLayout>




这样我们就可以实现用异步在网上获取图片了








阅读全文
2 0
原创粉丝点击