使用这些类是否有问题?此静态接口以后会使应用程序类出现任何问题吗?
public class App extends Application {
private static KareezAPI apiService;
private InternetConnectionListener mInternetConnectionListener;
public static final int DISK_CACHE_SIZE = 10 * 1024 * 1024; // 10 MB
public void setInternetConnectionListener(InternetConnectionListener listener) {
mInternetConnectionListener = listener;
}
public void removeInternetConnectionListener() {
mInternetConnectionListener = null;
}
public KareezAPI getApiService(Activity activity) {
if (apiService == null) {
apiService = provideRetrofit(KareezAPI.BASE_URL,activity).create(KareezAPI.class);
}
return apiService;
}
}
这是接口:
public interface KareezAPI{
String BASE_URL="https://baseurl.heroapp.com/";
@POST("register")
Call<RegisterResponse> RegisterUser( @Body RegisterData registerData);
@POST("login")
Call<RegisterResponse> LoginUser(@Body LoginData loginData); public interface LoginUserCallback{
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response);
public void onFailure(Call<RegisterResponse> call, Throwable t);
}
}
这是此接口和应用程序类的使用
((App) activity.getApplication()).getApiService(activity).LoginUser(loginData).enqueue(new
Callback<RegisterResponse>() {
@Override
public void onResponse(@NonNull Call<RegisterResponse> call, @NonNull
Response<RegisterResponse> response) {
loginUserCallback.onResponse(call, response);
}
@Override
public void onFailure(@NonNull Call<RegisterResponse> call, Throwable t) {
loginUserCallback.onFailure(call, t);
}
});
对我来说,将Api逻辑添加到Application类没有任何意义。您可以做的是在KareezAPI
界面中使用Retrofit,然后编写如下内容:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
KareezAPI service = retrofit.create(KareezAPI.class);
然后,当您要使用它时,写
KareezAPI.service.LoginUser().enqueue()...
您喜欢的地方。