1
我一直在使用Retrofit,使呼叫我的服務器的方法:回用改造方法
public class MainActivity extends AppCompatActivity {
// ... activity methods here, removed for simplicity ...
// Used to subscribe to a user given their userId
public void subscribeToUser(int userId) {
final ApiInterface apiService = ApiClient.createService(ApiInterface.class);
Call<BasicResponse> call = apiService.subscribe(userId);
call.enqueue(new Callback<BasicResponse>() {
@Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
}
我現在需要在其他活動使用同樣的方法(subscribeToUser()
),但它沒有任何意義將該方法複製並粘貼到其他活動中。然後我會有相同的代碼兩次。
所以我可以把方法放在一個地方讓它讓活動知道調用是否成功或失敗?我應該如何組織這個?
這裏是我ApiClient.java
類:
public class ApiClient {
public static final String API_BASE_URL = "http://www.website.com/api/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, final String authToken) {
if (authToken != null) {
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "Bearer " + authToken)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
}
這裏是我的ApiInterface.java
類:
public interface ApiInterface {
@FormUrlEncoded
@POST("subscribe")
Call<BasicResponse> subscribe(@Field("userId") Integer userId);
}
感謝。
您是否嘗試使用'BaseActivity extends AppCompatActivity'包含方法'subscribeToUser',之後'MainActivity'和其他活動擴展了BaseActivity。 –
@RoShanShan如果我需要在活動之外使用'subscribeToUser()'方法,就像在一個適配器中一樣? – user7669706
我認爲你可以在Activity中使用該方法並將結果發送到適配器。或者你可以發送'context'到你的適配器並使用((YouActivity)上下文).subscribeToUser()。 –