使用okhttp异步下载图片,保存到本地,并在系统相册中显示
2016-01-11 18:44
726 查看
//首先需要创建一个OkHttpClient实例
/**
* 下载图片并返回结果
/
/*将获取到的bitmap保存到本地,并在相册中有展示/
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(); }
相关文章推荐
- iOS开发网络篇之文件下载、大文件下载、断点下载
- 从僵尸网络追踪到入侵检测 第5章 使用Honeyd创建防御路由模板
- avaweb学习总结(八)——HttpServletResponse对象(二)
- ios 中使用https的知识
- [转载]Fiddler监控任意APK的HTTPS请求
- C++ 用libcurl库进行http通讯网络编程
- 从ZooKeeper源代码看如何实现分布式系统(三)高性能的网络编程
- C# post请求 HttpWebRequest
- centos6下httpd2.2的配置
- Android网络请求框架:Android-async-http简单使用
- 网络监控相关的一些命令
- android之Http两种post请求方式
- http-equiv
- HTTP 错误 404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求。
- [Python]网络爬虫(五):urllib2的使用细节与抓站技巧
- CentOS TinyProxy http(s)上网代理及置代理上网的方法
- ping +IP如何判断网络是否连接
- 网络爬虫的实现
- Neural Networks and Deep Learning学习笔记ch1 - 神经网络
- Python]网络爬虫(四):Opener与Handler的介绍和实例应用