Android-okhttp下载图片并保存(刷新图库)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_31057219/article/details/71212233

注意:下载和保存在子线程中进行。

//注意:下载和保存在子线程中进行。
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = getPic(url);//下载

                onSaveBitmap(bitmap, MainActivity.this);//保存到本地

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        iv4.setImageBitmap(bitmap);//显示图片
                    }
                });
            }
        }).start();

okhttp下载的方法:

 public Bitmap getPic(String url) {
        //获取okHttp对象get请求
        try {
            OkHttpClient client = new OkHttpClient();
            //获取请求对象
            Request request = new Request.Builder().url(url).build();
            //获取响应体
            ResponseBody body = client.newCall(request).execute().body();
            //获取流
            InputStream in = body.byteStream();
            //转化为bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(in);

            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

保存的方法:

 /*
    Android保存图片到系统图库:http://blog.csdn.net/xu_fu/article/details/39158747
    * */
    private void onSaveBitmap(final Bitmap mBitmap, final Context context) {
        // 第一步:首先保存图片
        //将Bitmap保存图片到指定的路径/sdcard/Boohee/下,文件名以当前系统时间命名,但是这种方法保存的图片没有加入到系统图库中
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");

        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 第二步:其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//   /storage/emulated/0/Boohee/1493711988333.jpg
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 第三步:最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
        //context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }

okhttp简单的封装(支持异步)后进行下载并显示图片:

工具类:

 class HttpUtil {
        private OkHttpClient client;

        public void getImage(String url, Callback callback) {
            //单例模式
            if (client == null) {
                client = new OkHttpClient();
            } else {
                Request request = new Request.Builder().url(url).build();
                //enqueue为OkHttp提供的异步方法
                client.newCall(request).enqueue(callback);
            }
        }
    }
 new HttpUtil().getImage(url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                byte[] bytes = response.body().bytes();
                final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                InputStream inputStream = response.body().byteStream();
//                Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);
                handler.post(new Runnable() {//主线程更新UI
                    @Override
                    public void run() {
                        iv6.setImageBitmap(bitmap);
                    }
                });
            }
        });
阅读更多

没有更多推荐了,返回首页