Android Okhttp缓存Cache,创建OkHttpClient实现
Android Okhttp使用缓存通过Cache实现。在创建OkHttpClient实现。构造Cache需要传递一个缓存文件目录已经缓存的大小尺寸。
下面演示一个简单功能,加载一张图片到一个ImageView,如果该连接下图片已经存在,那么即便在断网时候,也能使用缓存加载出来。
package zhangphil.app;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private OkHttpClient mOkHttpClient;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView image = (ImageView) findViewById(R.id.image);
File cacheDir = new File(this.getCacheDir(), "zhangphilcache");
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);
}
});
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消所有Okhttp的网络请求
mOkHttpClient.dispatcher().cancelAll();
}
}