glide默认的缓存图片路径地址_Android-Glide-从服务器下载图片至指定SD路径中

1.先封装一个SDFileHelper方法,通过Glide图片加载库保存服务器上的图片

String filePath = Environment.getExternalStorageDirectory() + File.separator + "A1";,自定义图片保存的位置

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() {

@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() + File.separator + "A1";

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();

}

}

2.在事件中调用

public class MainActivity extends AppCompatActivity {

private String url = "http://www.vorin.cn/storage/oilImage/test/tim1.jpeg";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button btn = (Button)findViewById(R.id.btn_get);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

SDFileHelper helper = new SDFileHelper(MainActivity.this);

helper.savePicture("tim1.jpeg", url);

}

});

}

}

3.若要加载大量图片

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button btn = (Button)findViewById(R.id.btn_get);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//100要换掉

for (int i = 1; i < 100; i++) {

String url = "http://www.vorin.cn/storage/oilImage/test/tim" + i + ".jpeg";

//取得最后一个/的下标

int index = url.lastIndexOf("/");

//将字符串转为字符数组

char[] ch = url.toCharArray();

//根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串

String informationId = String.copyValueOf(ch, index + 1, ch.length - index - 1);

SDFileHelper helper = new SDFileHelper(MainActivity.this);

helper.savePicture(informationId, url);

}

}

});

}

}

上述中i要通过接口获取jsons数据统计文件数量,会在下篇中讲到

你可能感兴趣的:(glide默认的缓存图片路径地址_Android-Glide-从服务器下载图片至指定SD路径中)