关闭

网络图片加载,实现了简单的三级缓存

标签: 布局网络缓存
627人阅读 评论(0) 收藏 举报
分类:

这个Demo有网络加载图片和简单的三级缓存功能。


这是布局

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

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入图片的URL" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="查看"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/imageView"
        android:scaleType="fitCenter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


Java代码

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private ImageView imageView;
    private static final int SUCCEED = 215;
    private static final int ERROR = 392;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCEED:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    imageView.setImageBitmap(bitmap);
                    break;
                case ERROR:
                    Toast.makeText(MainActivity.this, "获取图片失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        editText = (EditText) findViewById(R.id.editText);
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    public void onClick(View view) {

        //切换这里改变获得path的url
//        final String path = editText.getText().toString().trim();
        final String path = "http://img3.duitang.com/uploads/item/201409/15/20140915140123_WEH4N.png";

        final File file = new File(getCacheDir(), GetFileName(path));
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            Message obtain = Message.obtain();
            obtain.obj = bitmap;
            obtain.what = SUCCEED;
            handler.sendMessage(obtain);
        } else {
            if (TextUtils.isEmpty(path)) {
                Toast.makeText(this, "请输入图片的网址", Toast.LENGTH_SHORT).show();
                return;
            }
            new Thread() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(path);
                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                        //GET请求
                        httpURLConnection.setRequestMethod("GET");
                        //连接超时等待时间
                        httpURLConnection.setConnectTimeout(4000);
                        //网络读取超时时间
                        httpURLConnection.setReadTimeout(4000);

                        String contentType = httpURLConnection.getContentType();
                        Log.i("ContentType:", contentType);
                        int responseCode = httpURLConnection.getResponseCode();
                        if (responseCode == 200) {
                            InputStream inputStream = httpURLConnection.getInputStream();

                            byte[] bytes = new byte[1024];

                            int length;

                            FileOutputStream fileOutputStream = new FileOutputStream(file);

                            while ((length = inputStream.read(bytes)) != -1) {
                                fileOutputStream.write(bytes, 0, length);
                            }

                            fileOutputStream.close();

                            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                            //定义一个Message
                            Message message = Message.obtain();
                            //设置响应码
                            message.what = SUCCEED;
                            //设置object
                            message.obj = bitmap;
                            handler.sendMessage(message);
                            inputStream.close();
                        } else {
                            handler.sendEmptyMessage(ERROR);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    /**
     * http://img3.duitang.com/uploads/item/201409/15/20140915140123_WEH4N.png
     *
     * @return
     */
    private String GetFileName(String url) {
        int i = url.lastIndexOf("/");
        String substring = url.substring(i + 1);
        return substring;
    }

}


当然,还有个最重要的一步就是manifest中的权限

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


通过 GET 请求将网络上的图片数据通过流缓存到本地内存中,再缓存到本地磁盘当中,通过判断是否存在数据来进行本地缓存的操作,测试的时候网址写死了,如果想测试其他图片可以 path 那一块切换一下,这里我没有做图片压缩的处理,如果加载像素过高的图片可能会出现 OOM 的错误。

当然网络加载图片和三级缓存还有许多种方式,这只是其中的一种而已,仅供学习,实际开发中还是根据需求不同做出调整。


5
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2602次
    • 积分:76
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    文章分类
    文章存档