80 lines
2.6 KiB
Java
80 lines
2.6 KiB
Java
package com.gh.gamecenter.retrofit;
|
|
|
|
import android.content.Context;
|
|
|
|
import com.gh.common.constant.Config;
|
|
import com.gh.gamecenter.Injection;
|
|
import com.gh.gamecenter.retrofit.service.ApiService;
|
|
import com.gh.gamecenter.retrofit.service.DataService;
|
|
import com.gh.gamecenter.retrofit.service.UserseaService;
|
|
|
|
import java.io.File;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
import okhttp3.Cache;
|
|
import okhttp3.OkHttpClient;
|
|
import retrofit2.Retrofit;
|
|
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
|
|
import retrofit2.converter.gson.GsonConverterFactory;
|
|
|
|
/**
|
|
* Created by LGT on 2016/11/7.
|
|
* Retrofit 管理工具
|
|
*/
|
|
public class RetrofitManager {
|
|
|
|
private static RetrofitManager sInstance;
|
|
private static final byte[] LOCK = new byte[0];
|
|
private ApiService mApiService;
|
|
private DataService mDataService;
|
|
private UserseaService mUserseaService;
|
|
|
|
public static <T> T provideService(OkHttpClient client, String url, Class<T> serviceCls) {
|
|
return new Retrofit.Builder()
|
|
.client(client)
|
|
.addConverterFactory(GsonConverterFactory.create())
|
|
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
|
|
.baseUrl(url).build().create(serviceCls);
|
|
}
|
|
|
|
private RetrofitManager(Context context) {
|
|
final Cache cache = new Cache(new File(OkHttpCache.getCachePath(context)), 10 * 1024 * 1024); // 10Mb
|
|
|
|
final OkHttpClient okHttpClient = Injection.provideRetrofitBuilder()
|
|
.addInterceptor(new OkHttpCacheInterceptor(context))
|
|
.addInterceptor(new OkHttpRetryInterceptor(context))
|
|
.addNetworkInterceptor(new OkHttpNetworkInterceptor(context))
|
|
.connectTimeout(8, TimeUnit.SECONDS)
|
|
.cache(cache)
|
|
.build();
|
|
|
|
mApiService = provideService(okHttpClient, Config.API_HOST, ApiService.class);
|
|
mDataService = provideService(okHttpClient, Config.DATA_HOST, DataService.class);
|
|
mUserseaService = provideService(okHttpClient, Config.USERSEA_HOST, UserseaService.class);
|
|
}
|
|
|
|
public static RetrofitManager getInstance(Context context) {
|
|
if (sInstance == null) {
|
|
synchronized (LOCK) {
|
|
if (sInstance == null) {
|
|
sInstance = new RetrofitManager(context);
|
|
}
|
|
}
|
|
}
|
|
return sInstance;
|
|
}
|
|
|
|
public ApiService getApi() {
|
|
return mApiService;
|
|
}
|
|
|
|
public DataService getData() {
|
|
return mDataService;
|
|
}
|
|
|
|
public UserseaService getUsersea() {
|
|
return mUserseaService;
|
|
}
|
|
|
|
}
|