三级缓存 SD—内存—网络

顺序

先if内存

else  if  sd卡

else 网络获取

网络获取

网络获取 分别存入  内存和sd

先上代码  

创建一个用来自定义的类

public class ImageUtil {

    private static ImageUtil imageUtil;

    private static final String TAG = "ImageUtil";
    //3级内存
    LruCache<String, Bitmap> cache;

    private String path;
    ExecutorService executorService;
    private ImageUtil(){
        executorService = Executors.newSingleThreadExecutor();
        int l = (int) (Runtime.getRuntime().maxMemory() / 10);
        //init
        cache = new LruCache<String,Bitmap>(l){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }

    public static ImageUtil getInstance(){
        if(imageUtil == null){
            synchronized (ImageUtil.class){
                if(imageUtil == null){
                    imageUtil = new ImageUtil();
                }
            }
        }
        return imageUtil;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            Bitmap bitmap = (Bitmap) msg.obj;
            myListener.click(bitmap);

        }
    };

    public void loading(final String url){

        //http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg
        final String name = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));

        //1,先内存里面读取
        final Bitmap bitmap = cache.get(name);
        if(bitmap !=null){
            //
            Log.i(TAG, "loading: 从内存读取");
            //如果内存有,就读取
            myListener.click(bitmap);
        }else{
            //2,sd卡里读取
                Bitmap bitmap1 = BitmapFactory.decodeFile(new File(Environment.getExternalStorageDirectory() + File.separator + "image" + File.separator, name + ".jpg").getAbsolutePath());
                if(bitmap1 != null){
                    Log.i(TAG, "loading: 从sd卡读取");
                    myListener.click(bitmap1);
                    //放入到内存一份
                    cache.put(name,bitmap1);
                }else{
                    //3,从网络上读取
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            //从网络下载
                            Log.i(TAG, "run: 从网络中读取");
                            try {
                                URL url1 = new URL(url);
                                HttpURLConnection urlConnection =(HttpURLConnection) url1.openConnection();

                                if(urlConnection.getResponseCode() == 200){
                                    InputStream inputStream = urlConnection.getInputStream();
                                    //
                                    Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);

                                    //1,存sd
//                                Environment.getExternalStorageState()
                                    saveToSd(bitmap1, name);

                                    //2,存到内存
                                    cache.put(name,bitmap1);

                                    //发送
                                    Message obtain = Message.obtain();
                                    obtain.obj = bitmap1;
                                    handler.sendMessage(obtain);
                                }

                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                }
        }
    }

    /**
     * 保存到sd
     * @param bitmap1
     * @param name
     * @throws FileNotFoundException
     */
    private void saveToSd(Bitmap bitmap1, String name) throws FileNotFoundException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            ///storage/emulated/0/image/
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image" + File.separator);
            ///storage/emulated/0/image/2127.jgp
            if(!file.exists()){
                file.mkdirs();
            }
            File file1 = new File(file, name+".jpg");
            path = file1.getAbsolutePath();
            Log.i(TAG, "saveToSd: "+path);
            FileOutputStream fileOutputStream = new FileOutputStream(file1);
            bitmap1.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
        }
    }

    public interface MyListener{
        void click(Bitmap bitmap);
    }

    private MyListener myListener;

    public void setMyListener(MyListener myListener) {
        this.myListener = myListener;
    }
}

主类  MainActivity

public class MainActivity extends AppCompatActivity implements ImageUtil.MyListener {
    private Button btn;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        btn = (Button) findViewById(R.id.btn);
        img = (ImageView) findViewById(R.id.img);

        ImageUtil instance = ImageUtil.getInstance();
        instance.setMyListener(this);
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
    }



    public void loading(View view) {
        ImageUtil.getInstance().loading("http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg");
    }

    @Override
    public void click(Bitmap bitmap) {
        img.setImageBitmap(bitmap);
    }
}

附上           XML

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="loading"
        android:onClick="loading"
        android:id="@+id/btn"></Button>

    <ImageView
        android:src="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/img"></ImageView>
</LinearLayout>


嘿-----------------------最后可别忘记加上权限嗷·~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值