android 缓存使用简介

本文详细介绍了如何利用软引用优化图片加载过程,并将常用图片缓存到本地SD卡,减少网络请求,提升用户体验。同时,通过代码示例展示了将图片保存至SD卡的方法,确保资源的有效利用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接


网络图片在开发过程中,一般都将图片缓存到本地sd卡中(经常要使用的图片),方便下次直接引用而不再次请求网络耗费资源。而如果是自己开发搜索功能里有涉及到图片的显示,可以直接Map<String, SoftReference<Drawable>>,即软引用。

软引用重要代码代码:

package com.test.load;

 

import java.lang.ref.SoftReference;

import java.net.URL;

import java.util.HashMap;

import java.util.Map;

 

import android.graphics.drawable.Drawable;

import android.os.Handler;

import android.os.Message;

 

public class ThreadImgLoader {

  private Map<String, SoftReference<Drawable>> imageCache=new HashMap<String, SoftReference<Drawable>>();

  

   public Drawable loadDrawable(final String imgUrl, final ImageCallback callback){

      if (imageCache.containsKey(imgUrl)) {

        SoftReference<Drawable> sf=imageCache.get(imgUrl);

        if (sf.get()!=null) {

           return sf.get();

        }

      }

      final Handler handler=new Handler(){

        public void handleMessage(Message msg) {

           callback.imageLoaded((Drawable) msg.obj);

        }

      };

      new Thread(){

        public void run() {

           Drawable drawable=loadImgFromUrl(imgUrl);

           if (drawable!=null) {

              imageCache.put(imgUrl, new SoftReference<Drawable>(drawable));

              Message msg=handler.obtainMessage(0, drawable);

              handler.sendMessage(msg);

           }

        }

      }.start();

      return null;

   }

  

   public Drawable loadImgFromUrl(String imgUrl) {

      try {

        return Drawable.createFromStream(new URL(imgUrl).openStream(), "src");

      } catch (Exception e) {

        return null;

      }

   }

  

   public interface ImageCallback{

      public void imageLoaded(Drawable drawable);

   }

}

 下面是缓存到SD卡的重要代码,当然你也可以搜索一下,这方面的东西很多。WeakHashMap也是使用了软引用,你可以去看它的源代码:

package com.test;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.util.WeakHashMap;

 

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.BitmapFactory;

import android.os.Environment;

 

public class MyImgCache extends WeakHashMap<String, Bitmap> {

   private static MyImgCache myImgCache=new MyImgCache();

   private static final String CACHE_FILE="/MyXiaoCaiImg";

   public static MyImgCache getInstance(){

      return myImgCache;

   }

  

   public boolean isBitmapExist(String url) {

      boolean isexist=false;

      String name=changeUrlName(url);

      String filePath=isMakeFile();

      File file=new File(filePath, name);

      if (containsKey(url)) {

        isexist=true;

      }else if (file.exists()) {

        String path=file.getAbsolutePath();

        System.out.println(path);

        Bitmap bitmap=BitmapFactory.decodeFile(path);

        if (bitmap!=null) {

           put(url, bitmap, false);

           isexist=true;

        }

      }

      return isexist;

   }

 

   private String changeUrlName(String url) {

      String name = url.replaceAll(":", "_");

      name = name.replaceAll("//", "_");

      name = name.replaceAll("/", "_");

      name = name.replaceAll("=", "_");

      name = name.replaceAll(",", "_");

      name = name.replaceAll("&", "_");

      return name;

   }

  

   private String isMakeFile() {

      String rootpath = null;

      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

        rootpath = Environment.getExternalStorageDirectory().toString();

      }

      String filepath = rootpath + CACHE_FILE;

      File file = new File(filepath);

      if (!file.exists()) {

        file.mkdirs();

      }

      return filepath;

   }

 

   public Bitmap put(String key, Bitmap value) {

      String name=changeUrlName(key);

      String filePath=isMakeFile();

      File file = new File(filePath, name);

      OutputStream outputStream = null;

      try {

        outputStream = new FileOutputStream(file);

        value.compress(CompressFormat.JPEG, 100, outputStream);

        outputStream.flush();

        outputStream.close();

        outputStream = null;

      } catch (Exception e) {

        e.printStackTrace();

      }

      return super.put(key, value);

   }

 

   public Bitmap put(String key, Bitmap value, boolean b) {

      if (b) {

        return this.put(key, value);

      }else {

        return super.put(key, value);

      }

   }

 

}


### 扣子智能体平台功能与使用说明 #### 平台概述 扣子Coze)是由字节跳动推出的一款面向终端用户的智能体开发平台[^3]。该平台支持用户通过零代码或低代码方式快速构建基于人工智能大模型的各种智能体应用,并能够将其部署至其他网站或者通过 API 集成到现有的系统中。 #### 快速搭建智能体 无论是具备还是缺乏编程基础的用户,都能够借助扣子平台迅速创建一个 AI 智能体。例如,可以参照一篇教程中的实例来学习如何打造一个解决日常生活问题的小助手[^1]。这不仅降低了技术门槛,还使得更多的人有机会参与到智能化工具的设计过程中去。 #### 插件系统的利用 为了进一步增强所建智能体的能力,在其技能配置环节可加入不同类型的插件。一旦添加成功,则可以在编写提示语句的时候直接调用这些插件,亦或是融入自动化流程里实现更复杂操作逻辑的目的[^2]。这种灵活运用外部资源的方法极大地拓宽了单个智能体所能覆盖的应用场景范围。 ```python # 示例:假设我们有一个简单的 Python 脚本用于模拟调用某个插件功能 def call_plugin(plugin_name, parameters): result = f"Plugin {plugin_name} called with params: {parameters}" return result example_call = call_plugin("weather", {"location": "Beijing"}) print(example_call) ``` 上述代码片段仅作为概念展示之用,实际情况下具体实现会依据官方文档指导完成。 #### 总结 综上所述,扣子智能体平台提供了便捷高效的途径让用户无需深厚编码背景即可打造出满足特定需求的AI解决方案;同时它开放性强允许接入第三方服务从而提升整体性能表现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值