OkHttp缓存设置

指定缓存地址就行了cache(mCache)

public class MainActivity extends AppCompatActivity {
    private ImageView image;
    private OkHttpClient mOkHttpClient = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewById(R.id.image);
    }

    String url;
    int count = 0;

    public void request(View view) {
        switch (view.getId()) {
            case R.id.btn_request:
                count++;
                if (count % 2 == 0) {
                    url = "https://www.baidu.com/img/bd_logo1.png";
                } else {
                    url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1562668428835&di=9adb708a336be20afa7f5241ccb9906e&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3mqqgy6UQ54J16Zed%26690";
                }
                requestImage(url);
                break;
        }
    }

    /**
     * 请求网络
     */
    private void requestImage(String url) {
        Log.e("requestImage===", url);
        File cacheDir = new File(getProjectCachePath(MainActivity.this), "okhttp");
        Cache mCache = new Cache(cacheDir, 8 * 1024 * 1024);
        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();

        mOkHttpClient = mBuilder
                .connectTimeout(10, TimeUnit.SECONDS) //连接超时阈值
                .writeTimeout(10, TimeUnit.SECONDS) //写超时阈值
                .readTimeout(10, TimeUnit.SECONDS)  //读超时阈值
                .retryOnConnectionFailure(true) //当失败后重试
                .cache(mCache)
                .build();

//        String url = "https://www.baidu.com/img/bd_logo1.png";
        Request mRequest = new Request.Builder().url(url).build();

        mOkHttpClient.newCall(mRequest).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    byte[] bytes = response.body().bytes();
                    final Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            image.setImageBitmap(bmp);
                        }
                    });
                }
            }
        });
    }

    public static String getProjectCachePath(Context context) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //取消所有Okhttp的网络请求
        mOkHttpClient.dispatcher().cancelAll();
    }
}

 

你可能感兴趣的:(Android,零碎知识点记录)