您的位置:首页 > 理论基础 > 计算机网络

利用缓存存储网络下载的图片

2016-03-03 20:43 423 查看
一、当客户第一次获取网络的图片时,是从网络上获取的,我们可以将图片写到客户的内存中去,在客户重新打开文件的时候,直接在存储中读取;

二、实现,第一截取客户从网络读入的输入流,开启输出流模式,将其保存到输出流的文件中,再从文件读取到客户界面;

三、逻辑实现:第一先判断文件是否存在,如果存在则直接在UI线程显示图片,如果不存在,则通过网络读取图片,并写入存储;

public class MainActivity extends AppCompatActivity {
    static ImageView imageView=null;
    static MainActivity ma;
    static Handler handler=new Handler(){
        //此方法在主线程中运用,用于刷新UI
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 1:
                     //将Image对象显示到图片里面去
                        imageView.setImageBitmap((Bitmap) msg.obj);
                        break;
                case 2:
                    Toast.makeText(ma,"请求失败",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.image1);
        ma=this;
       }
    public void click(View view){

        final String path="http://sc.chinaz.com/tupian/151110391763.htm\n";
        final File file=new File(getCacheDir(),getFile(path));
        //判断缓存是否存在文件
        if(file.exists()){
            //如果文件存在,直接在位图显示文件内部的文件
            imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
        }else{
            Thread thread=new Thread(){
                public void run(){
                    try {
                        //将网址封装成一个URL对象
                        URL url=new URL(path);
                        //获取客户端与服务器连接的对象,此时还未产生连接
                        HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                        //对连接对象初始化,建立连接对象的初始化,客户端向服务器端发送的请求
                        //设置请求方法,注意大写,客户端向服务器请求数据总共就两个,一个get,一个post,提交数据的时候用post
                        connection.setRequestMethod("GET");
                        //设置建立连接超时
                        connection.setConnectTimeout(5000);
                        //设置读取超时
                        connection.setReadTimeout(8000);
                        //发送请求与服务器建立连接
                        connection.connect();
                        //这是服务器的请求码,如果响应吗为200,说明请求成功
                        if(connection.getResponseCode()==200){
                            //获取输入流,读取服务器的流,服务器与客户端都是通过流的方式交互的,服务器通过流写给客户端
                            InputStream inputStream=connection.getInputStream();
                            FileOutputStream fileOutputStream=new FileOutputStream(file);
                            int len=0;
                            byte[] b=new byte[1024];
                            while((len=inputStream.read(b))!=-1){
                                fileOutputStream.write(b,0,len);
                            }
                            fileOutputStream.close();
                            //将文件内的图片解析到位图中
                            Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
                            //Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
                            //将消息发送给消息队列
                            //创建message,最好是利用obtain()创建
                            Message msg=Message.obtain();
                            //消息对象可以携带数据,如果携带多个对象,那么obj设置成一个数组就可
                            msg.obj=bitmap;
                            msg.what=1;
                            handler.sendMessage(msg);
                        }else{
                            Message msg=Message.obtain();
                            msg.what=2;
                            handler.sendMessage(msg);
                            //  Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }
    //截取文件名
    public String getFile(String path){
        int index=path.lastIndexOf("/");
        //获取最后一个/后面的文字内容
        return path.substring(index+1);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: