android SD卡缓存

步骤
1.发送http请求 获取JSON对象,解析JSON
2.判断SD上否可以使用 得到图片路径,截取图片名字
3.查看SD卡上否有图片,有使用本地图片 没有使用根据解析的JSON 地址去下载图片 显示出来  缓存到保存到SD卡上


步骤1


String path = getResources().getString(R.string.serverurl); // 获取本地的服务器路径
URL url = new URL(path);// 创建URL 
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//获取HttpURLConnection对象
conn.setRequestMethod("GET");// 发送一个 get请求
conn.setConnectTimeout(5000);// 设置超时时间
if (conn.getResponseCode() == 200) { //  返回状态吗
InputStream is = conn.getInputStream(); // 以流的方式返回


ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
Bytes by=  bos.toByteArray();


String json = new String(by);
 //解析json....




 步骤2,3




File file = new File(Environment.getExternalStorageDirectory(), //创建文件夹
getFileName(imagePath));


if(flie.exists()&&file.lengh() > 0){ //判断文件是否存在 并且有内容


System.out.println("使用sd卡缓存");
iv.setImageURI(Uri.fromFile(file));


}else{


//从服务器上下载图片
BitMap bitMap = etBitmap(String path) //JSON解析到的 图片地址
if(bitmap =!null){
//显示图片}
FileOutputStream fos = new FileOutputStream(file); 
bitmap.compress(CompressFormat.JPEG, 100, fos); //缓存到SD卡上


}
}


注释: 文件 根据路径就准备好了 (不管是否存在先创建)所以不关系 缓存到SD卡上的 图片


ile file = new File(Environment.getExternalStorageDirectory(), //创建文件夹
“图片A”);


FileOutputStream fos = new FileOutputStream(file); 
bitmap.compress(CompressFormat.JPEG, 100, fos); //缓存到SD卡 图片为A








-------------------------------
/**
* 获取资源的名称

* @param path
* @return
*/
private String getFileName(String path) {
return path.substring(path.lastIndexOf("/") + 1, path.length());
}






/**
* 获取一张网络的图片
* @param path
* @return
*/
public static Bitmap getBitmap(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 指定一下 http协议的请求方式
conn.setRequestMethod("GET");
// 设置连接超时的时常
conn.setConnectTimeout(5000);
// 指定http请求的参数
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C)");


if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}


}
0
0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值