项目中三大库(okhttp,glide,greenDao)的优化点

308 阅读1分钟

okhttp

post请求,没有缓存,通过Intercept 实现

public class EnhancedCacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if(request.header("cache")!=null){
            String url = request.url().toString();
            RequestBody requestBody = request.body();
            Charset charset = Charset.forName("UTF-8");
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (request.method().equals("POST")) {
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(Charset.forName("UTF-8"));
                }
                Buffer buffer = new Buffer();
                try {
                    requestBody.writeTo(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sb.append(buffer.readString(charset));
                buffer.close();
            }
            Log.d(CacheManager.TAG, "EnhancedCacheInterceptor -> key:" + sb.toString());
            if(!response.isSuccessful()){
                return response;
            }
            ResponseBody responseBody = response.body();
            MediaType contentType = responseBody.contentType();

            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();

            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            String key = sb.toString();
            //服务器返回的json原始数据
            String json = buffer.clone().readString(charset);

            CacheManager.getInstance().putCache(key, json);
            Log.d(CacheManager.TAG, "put cache-> key:" + key + "-> json:" + json);
        }
        return response;
    }
}

添加LogIntercept

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

添加Intercept,处理header:token,userid

clientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                if (MainApplication.getToken() != null && MainApplication.getUserId() != null) {
                    request = request.newBuilder().addHeader("token", MainApplication.getToken())
                            .addHeader("user_id", MainApplication.getUserId())
                            .build();
                } else if (MainApplication.getUserId() != null) {
                    request = request.newBuilder().addHeader("user_id", MainApplication.getUserId())
                            .build();
                }
                return chain.proceed(request);
            }
        });

Glide

图片显示格式RGB_565,改成ARGB_888

请求默认HttpConnection, 改成okhttp

public class SimpleGlideModule implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
    }
}

GreenDao

升级

### 定义接口,以及升级类,在各版本中实现sql
public interface Migration {

    void migrate(SQLiteDatabase db);

}

public class V1Migration implements Migration{
	
}

自带一张表,用生成好的数据库

自定义AXZHMaster ,改写onupdate ,实现升级和用现有库

public class AXZHMaster extends DaoMaster{

    public AXZHMaster(SQLiteDatabase db){
        super(db);
    }

    private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<>();

    static {
//        ALL_MIGRATIONS.put(1, new V1Migration());

    }
    /** WARNING: Drops all table on Upgrade! Use only during development. */
    public static class DevOpenHelper extends DatabaseOpenHelper {

        public DevOpenHelper(Context context, String name) {
            super(context, name, SCHEMA_VERSION);
        }

        public DevOpenHelper(Context context, String name, CursorFactory factory) {
            super(context, name, factory, SCHEMA_VERSION);
        }


        @Override
        public void onCreate(Database  db) {
            Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
            createAllTables(db, true);
        }

        @Override
        public void onUpgrade(Database  db, int oldVersion, int newVersion) {
            Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
//            dropAllTables(db, true);
//            onCreate(db);
            createAllTables(db, true);
            SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
            executeMigrations((SQLiteDatabase) db.getRawDatabase(), migrations.keySet());
        }

        private void executeMigrations(final SQLiteDatabase paramSQLiteDatabase, final Set<Integer>
                migrationVersions) {
            for (final Integer version : migrationVersions) {
                ALL_MIGRATIONS.get(version).migrate(paramSQLiteDatabase);
            }
        }
    }


}