当前位置: 移动技术网 > 移动技术>移动开发>Android > android中Glide实现加载图片保存至本地并加载回调监听

android中Glide实现加载图片保存至本地并加载回调监听

2019年07月24日  | 移动技术网移动技术  | 我要评论

glide 加载图片使用到的两个记录

glide 加载图片保存至本地指定路径

/**
     * glide 加载图片保存到本地
     *
     * imgurl 图片地址
     * imgname 图片名称
     */
    glide.with(context).load(imgurl).asbitmap().tobytes().into(new simpletarget<byte[]>() {
      @override
      public void onresourceready(byte[] bytes, glideanimation<? super byte[]> glideanimation) {
        try {
          savabitmap(imgname, bytes);
        } catch (exception e) {
          e.printstacktrace();
        }
      }
    });

// 保存图片到手机指定目录
  public void savabitmap(string imgname, byte[] bytes) {
    if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
      string filepath = null;
      fileoutputstream fos = null;
      try {
        filepath = environment.getexternalstoragedirectory().getcanonicalpath() + "/myimg";
        file imgdir = new file(filepath);
        if (!imgdir.exists()) {
          imgdir.mkdirs();
        }
        imgname = filepath + "/" + imgname;
        fos = new fileoutputstream(imgname);
        fos.write(bytes);
        toast.maketext(context, "图片已保存到" + filepath, toast.length_short).show();
      } catch (ioexception e) {
        e.printstacktrace();
      } finally {
        try {
          if (fos != null) {
            fos.close();
          }
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    } else {
      toast.maketext(context, "请检查sd卡是否可用", toast.length_short).show();
    }
  }

glide 加载图片回调方法

glide.with(context).load(imgurl)
        .listener(new requestlistener<string, glidedrawable>() {
          @override
          public boolean onexception(exception e, string model,
                        target<glidedrawable> target,
                        boolean isfirstresource) {
            // 可替换成进度条
            toast.maketext(context, "图片加载失败", toast.length_short).show();
            return false;
          }

          @override
          public boolean onresourceready(glidedrawable resource, string model,
                          target<glidedrawable> target,
                          boolean isfrommemorycache,
                          boolean isfirstresource) {
            // 图片加载完成,取消进度条
            toast.maketext(context, "图片加载成功", toast.length_short).show();
            return false;
          }
        }).error(r.mipmap.ic_launcher_round)
        .diskcachestrategy(diskcachestrategy.all)
        .into(imageview);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网