您的位置:首页 > 理论基础 > 计算机网络

使用okhttp异步下载图片,保存到本地,并在系统相册中显示

2016-01-11 18:44 726 查看
//首先需要创建一个OkHttpClient实例

private OkHttpClient mOkHttpClient = new OkHttpClient();
private Handler mDelivery = new Handler(Looper.getMainLooper());


/**

* 下载图片并返回结果

/

private void loadImage(final String url, final ResultCallBack callBack) {
Request request = new Request.Builder().url(url).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
mDelivery.post(new Runnable() {
@Override
public void run() {
callBack.onError(request, e);
}

@Override
public void onResponse(Response response) {
InputStream is = null;
try {
is = response.body.byteStream();
is.reset();
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = false;
final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
mDelivery.post(new Runnable() {
@Override
public void run() {
callBack.onResponse(bm);
}
});
} catch (Exception e) {
} finally {
if (is != null) {
is.close();
}
}

}

});
}
});
}


/*将获取到的bitmap保存到本地,并在相册中有展示/

private void onSaveBitmap(Bitmap mBitmap, Context context) {
new Thread(new Runnable() {
@Ovrride
public void run() {
String photoPath = Environment.getExternalStorageDirectory
.getAbsolutePath +/test / image / +test.jpg;
//创建文件对象,用来存储新的图像文件
File file = new File(photoPath);
//创建文件
file.creatNewFile();
//定义文件输出流
FileOutputStream fOut = new FileOutputStream(file);
//将bitmap存储为jpg格式的图片
mBitmap.compess(Bitmap.CompessFormat.JPEG, 100, fout);
fout.flush();//刷新文件流
fout.close();

//文件存储已经完毕,保存的图片没有加入到系统图库中
//,此时需要发送广播,刷新图库,很简单几行代码搞定
Intent intent =
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File(photoPath));
intent.setDate(uri);
context.sendBroadcast(intent)

}
}).start();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: