我已经创建了一个枚举单子Retrofit类。
public enum RetrofitClient {
INSTANCE;
private Retrofit retrofit;
RetrofitClient() {
retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.BASE_URL)
.client(okHttpClientInitialization().build())
.build();
}
public API callEndPoint() { return retrofit.create(API.class); }
private OkHttpClient.Builder okHttpClientInitialization() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(3, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES);
//initialize the header
retrofitHeader(httpClient);
return httpClient;
}
private void retrofitHeader(OkHttpClient.Builder okHttpClient) {
okHttpClient.addInterceptor(chain -> {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().header("Authorization", "secret-key")
.addHeader("lang", MyTools.getCurrentLanguage(context.getApplicationContext()));//ERORR
return chain.proceed(newRequest.build());
});
}
}
但问题是如何通过上下文来使用它与 getCurrentLanguage有什么方法可以做到这一点?而不改变枚举或任何干净的代码?
Android中的Application类是Android应用中的基础类,它包含所有其他组件,如活动和服务。
下面是RetrofitApiClient的一个例子。
public class ApiClient {
private static final String BASE_URL = "https://www.gaida.nepal.app/api/";
private static File httpCacheDirectory = new File(AppApplication.getAppContext().getCacheDir(), "new_responses");
private static int cacheSize = 10 * 1024 * 1024; // 10 MiB
private static Cache cache = new Cache(httpCacheDirectory, cacheSize);
private static Retrofit retrofit = null;
public static Retrofit getClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// builder.interceptors().add(interceptor);
// builder.authenticator(new ApiTokenAuthenticator());
OkHttpClient httpClient = builder
.readTimeout(15, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
// .addInterceptor(new ApiInterceptor())
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
RxJava2CallAdapterFactory rxJava2CallAdapterFactory = RxJava2CallAdapterFactory.createWithScheduler(Schedulers.computation());
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.client(httpClient)
.build();
}
return retrofit;
}
}
应用类
public class AppApplication extends Application implements Application.ActivityLifecycleCallbacks, Thread.UncaughtExceptionHandler {
private static AppApplication tourismApplication;
private static SharedPreferences sharedPreferences;
private static boolean isActive;
private Activity activity;
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
tourismApplication = this;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getAppContext());
}
public static AppApplication getInstance() {
return tourismApplication;
}
public static boolean isActivityVisible() {
return isActive;
}
public static Context getAppContext() {
return tourismApplication.getApplicationContext();
}
public static SharedPreferences getSharedPreference() {
return sharedPreferences;
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
isActive = true;
}
@Override
public void onActivityResumed(Activity activity) {
isActive = true;
}
@Override
public void onActivityPaused(Activity activity) {
isActive = false;
}
@Override
public void onActivityStopped(Activity activity) {
isActive = false;
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
isActive = false;
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Intent intent = new Intent(activity, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(AppApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager) AppApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
activity.finish();
System.exit(2);
}
在Manifest.xml中声明应用类,如
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@drawable/ic_logo_onn_app"
android:supportsRtl="true"
android:name=".helpers.AppApplication"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
</application>
现在获取应用程序上下文为
AppApplication.getAppContext()
RetrofitApi拦截器
public class ApiInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request originalRequest = chain.request();
if (Utilities.getLoginResponse() == null || TextUtils.isEmpty(Utilities.getLoginUserToken())) {
return chain.proceed(originalRequest);
}
Request request = originalRequest.newBuilder()
.addHeader("Authorization", Utilities.getLoginUserToken())
.addHeader("Accept", "Accept: application/x.school.v1+json")
.header("Cache-Control", String.format("max-age=%d", 50000))
.build();
return chain.proceed(request);
}
}
获得选定语言的例子。
public static String getSelectedLanguage() {
return AppApplication.getSharedPreference().getString(AppConstants.SELECTED_LANGUAGE,"en");
}