okhttp下载保存图片并更新图库

实现效果图:

okhttp下载保存图片并更新图库_第1张图片

 

清单文件,下载和读写文件

 
    
    
    
    
    

 在这里进行主要的功能实现,包括两个方式启动线程,使用okhttp做图片下载和get请求,然后保存图片文件到本地,把图片文件转换为数据流,写入系统图片文件夹,然后通知图库对于图片文件进行更新

package com.example.administrator.testz;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    private TextView tv;
    private ImageView iv;
    private String url = "https://img-my.csdn.net/uploads/201508/05/1438760726_5120.jpg";
    private String urls = "https://b-ssl.duitang.com/uploads/item/201407/18/20140718154214_BFeQt.thumb.1400_0.jpeg";
    private String url2 = "http://n.sinaimg.cn/sinacn10119/200/w640h360/20181223/4c27-hqqzpku7644786.jpg";

    final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };



    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==100){
                //消息接收器
                Bitmap a = (Bitmap) msg.obj;
                onSaveBitmap(a,MainActivity.this);
                iv.setImageBitmap(a);
            }
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView)findViewById(R.id.tv);
        iv = (ImageView)findViewById(R.id.iv);

         doCheckPermission(); //android7.0开启文件权限

       // getInter(); 普通的okhttp的get请求方式
       // getRunnnanle(); 第一种线程启动方式
        getRunnnanle2();

    }

    //检查所需的全部权限
    public boolean doCheckPermission() {
        PermissionsChecker mPermissionsChecker = new PermissionsChecker(MainActivity.this);
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 0x12);
            return false;
        }
        return true;
    }


    //图片保存到本地
    private void onSaveBitmap(final Bitmap bitmap, final Context context) {
        File appDir = new File(Environment.getExternalStorageDirectory(),"wang");
        if(!appDir.exists()){
            appDir.mkdir();
        }
        String filename = System.currentTimeMillis()+".jpg";
        File file = new File(appDir,filename);
        try {
            /*
            Bitmap.CompressFormat format 图像的压缩格式;
            int quality 图像压缩率,0-100。 0 压缩100%,100意味着不压缩;
            OutputStream stream 写入压缩数据的输出流;
            */
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos); //质量压缩  10倍
            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);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://"+file)));
    }

    //第二种线程启动方式
    private void getRunnnanle2() {
        MyThread2 mythread2 = new MyThread2();
        Thread thread = new Thread(mythread2);
        thread.start();
    }

    //接口实现启动线程
    class MyThread2 implements Runnable{
        @Override
        public void run() {
            final Bitmap bitmap = getPic(url2);
            Message msg = new Message();
            msg.what=100;
            msg.obj = bitmap;
            handler.sendMessage(msg);
        }
    }


    //第一种方式启动线程
    private void getRunnnanle() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = getPic(urls);
                Message msg = new Message();
                msg.what=100;
                msg.obj = bitmap;
                handler.sendMessage(msg);
            }
        }).start();
    }


    //okhttp下载图片
    private Bitmap getPic(String url) {
        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 = BitmapFactory.decodeStream(in);
            return bitmap;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    //普通的okhttp网络请求
    private void getInter() {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("https://github.com/hongyangAndroid")
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("TAG","wang==onFailure");
            }

            @Override
            public void onResponse(Response response) throws IOException {

                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         tv.setText(res);
                        Log.e("TAG","wang==onResponse成功了"+res);
                    }
                });
            }
        });
    }





}

3.android7.0以后需要对文件进行权限申请


import android.content.Context;
        import android.content.pm.PackageManager;
        import android.os.Build;
        import android.support.v4.content.ContextCompat;


public class PermissionsChecker {
    private final Context mContext;

    public PermissionsChecker(Context context) {
        mContext = context.getApplicationContext();
    }

    // 判断权限集合
    public boolean lacksPermissions(String... permissions) {
        for (String permission : permissions) {
            if (lacksPermission(permission)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否缺少权限
    private boolean lacksPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ContextCompat.checkSelfPermission(mContext, permission) ==
                    PackageManager.PERMISSION_DENIED;
        }
        return false;
    }

}

 

你可能感兴趣的:(android,学习)