发布于 2017-10-11 12:03:53 | 160 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


本篇文章主要介绍了Android中Glide实现超简单的图片下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

本文介绍了Glide实现超简单的图片下载功能,具体步骤如下:

添加依赖


compile 'com.github.bumptech.glide:glide:3.7.0'

添加权限


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

工具类代码


public class SDFileHelper {

  private Context context;

  public SDFileHelper() {
  }

  public SDFileHelper(Context context) {
    super();
    this.context = context;
  }

  //Glide保存图片
  public void savePicture(final String fileName, String url){
    Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
      @Override
      public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
        try {
          savaFileToSD(fileName,bytes);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  //往SD卡写入文件的方法
  public void savaFileToSD(String filename, byte[] bytes) throws Exception {
    //如果手机已插入sd卡,且app具有读写sd卡的权限
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String filePath = Environment.getExternalStorageDirectory().getCanonicalPath()+"/budejie";
      File dir1 = new File(filePath);
      if (!dir1.exists()){
        dir1.mkdirs();
      }
      filename = filePath+ "/" + filename;
      //这里就不要用openFileOutput了,那个是往手机内存中写数据的
      FileOutputStream output = new FileOutputStream(filename);
      output.write(bytes);
      //将bytes写入到输出流中
      output.close();
      //关闭输出流
      Toast.makeText(context, "图片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
    } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
  }

}

然后再需要的地方调用


 SDFileHelper helper = new SDFileHelper(MainActivity.this);
 helper.savePicture("bg.jpg",url);


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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务