程序员

okhttp 无网本地缓存实现

2016-10-25  本文已影响1573人  Alien的小窝

再也无需手动写入复杂的缓存实现了

所需权限


    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

实现代码

public class MainActivity extends AppCompatActivity {
    OkHttpClient ok;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        OkHttpClient okHttpClient = getOk();

        Request request = new Request.Builder().url("http://need88.com").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                final String message = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private OkHttpClient getOk() {
        if (ok == null) {
            synchronized (OkHttpClient.class) {
                if (ok == null) {
                    initOk();
                }
            }
        }
        return ok;
    }

    void initOk(){

        File httpCacheDirectory = new File("/sdcard", "cache_xx");

        //Cache cache  = new Cache(this.getCacheDir(), 10240 * 1024);
        Cache cache  = new Cache(httpCacheDirectory, 10240 * 1024 * 10); //10M
        OkHttpClient okHttpClient = new OkHttpClient();

        ok= okHttpClient.newBuilder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {                     
                        Request request = chain.request();
                        Log.e("MainActivity", "新请求 =request==" + request.toString());

                        Response response = chain.proceed(request); 
                        Response response_build ;
                        if (NetUtil.checkNet(MainActivity.this)) {

                            int maxAge = 60 * 60*24; // 有网络的时候从缓存1天后失效
                            response_build = response.newBuilder()
                                    .removeHeader("Pragma")
                                    .removeHeader("Cache-Control")
                                    .header("Cache-Control", "public, max-age=" + maxAge)
                                    .build();
                        } else {
                            int maxStale = 60 * 60 * 24 * 28; // // 无网络缓存保存四周
                            response_build = response.newBuilder()
                                    .removeHeader("Pragma")
                                    .removeHeader("Cache-Control")
                                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                    .build();
                        }

                        return response_build;
                    }
                })
                .cache(cache)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }
}

附上常用的判断网络权限工具类

package com.syntc.cacheok;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Administrator on 2015/11/23.
 */
public class NetUtil {

    //判断当前手机联网的渠道

    public static boolean checkNet(Context context){
        boolean wifiConnected = isWIFIConnected(context);
        boolean mobileConnected = isMOBILEConnected(context);
        boolean youxian = isYouXian(context);
        if(wifiConnected==false && mobileConnected== false&&youxian==false){
            //如果都没有连接,提示用户当前没有网络
            return false;
        }
        return true;
    }

    private static boolean isYouXian(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }

    public static boolean isMOBILEConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if(networkInfo !=null && networkInfo.isConnected()){
            return true;
        }
        return false;
    }

    private static boolean isWIFIConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(networkInfo !=null && networkInfo.isConnected()){
            return true;
        }
        return false;
    }

    // 新方法
    public static boolean isConn(Context context){
        boolean bisConnFlag=false;
        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if(network!=null){
            bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }
}

上一篇下一篇

猜你喜欢

热点阅读