android 实现从网络上抓取图片并显示在手机上

遇到的问题

      之前在学习android开发视频的时候,学习到从网络上下载图片并显示,但发现会报 NetworkOnMainThreadException,后来几经查证发现,在android 中实现网络访问等操作时由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会出现假死的现象,产生很不好的用户体验。所以,默认的情况下如果直接在主线程中访问就报出了这个异常,名字是NetworkOnMainThreadException

解决该问题的办法

1. 独立线程

2. 异步线程AsyncTask

3. StrictMode修改默认的策略


这里采用第一种方法来实现功能:


首先要注意在功能清单文件中加上访问网络的权限:



接下来编写工具类,主要用于从网络中读取数据

工具类1:

package StreamTool;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by Administrator on 2015/11/30.
 */
public class Streamtool {
    public static byte[] readDate(InputStream inputStream)throws Exception
    {
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        int len=0;
        byte[] buffer=new byte[1024];
        while((len=inputStream.read(buffer))!=-1)
        {
            outputStream.write(buffer,0,len);
        }
       inputStream.close();
        return  outputStream.toByteArray();
    }
}


工具类2,这里为了方便测试,直接将访问的图片路径写死了,也可以自己输入

package StreamTool;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2015/11/30.
 */
public class GetImage {
    public static final String PATH="http://docs.ebdoor.com/Image/ProductImage/0/3006/30060407_1.jpg";
    public static final int ONE_SECOND=1000;
    public static byte[] getNetimage()throws Exception
    {
        URL url=new URL(PATH);
        HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setReadTimeout(5 * ONE_SECOND);
        InputStream inputStream=httpURLConnection.getInputStream();
        return Streamtool.readDate(inputStream);
    }
}

 
  

主代码:

package com.example.administrator.getimageapplication;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import StreamTool.GetImage;


public class GetImageActivity extends Activity {
    private static final String TAG="GetImageActivity";
    private Button button;
    private ImageView imageView;
    private Thread mthread;
    private static final int MSG_SUCCESS=1;
    private static final int MSG_FAILE=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_image);
        button=(Button)findViewById(R.id.show);
        imageView=(ImageView)findViewById(R.id.showimage);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mthread==null)
                {
                    mthread=new Thread(runnable);
                    mthread.start();
                }
                else
                {
                    Toast.makeText(GetImageActivity.this,R.string.start_sucess,Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    private Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case MSG_SUCCESS:
                    imageView.setImageBitmap((Bitmap) msg.obj);
                    Toast.makeText(GetImageActivity.this,R.string.show_sucess,Toast.LENGTH_LONG).show();
                    break;
                case MSG_FAILE:
                    Toast.makeText(GetImageActivity.this,R.string.show_faile,Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            Bitmap bitmap=null;
            try
            {
                byte[] date=GetImage.getNetimage();
                bitmap= BitmapFactory.decodeByteArray(date,0,date.length);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                Log.e(TAG, e.toString());
                handler.obtainMessage(MSG_FAILE).sendToTarget();
                return;
            }
            handler.obtainMessage(MSG_SUCCESS,bitmap).sendToTarget();
        }
    };

}

实现结果:

android 实现从网络上抓取图片并显示在手机上_第1张图片





注:本人新手学习,有什么不足的地方恳请大家给出自己的意见,共同学习共同进步









你可能感兴趣的:(android,图片,网络,线程,handler)