//首先需要创建一个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();
}