我要在我的下一个Android项目中使用Retrofit 2.1.0。我想使用设计模式,因此为每个REST调用创建单独的类,即
IBalanceService.java
public Interface IBalanceService{ @GET("users/{username}") void getUser(@Path("username") String username, Callback<User> cb); }
BalanceRestClient.java
public class BalanceRestClient{ String username = "Makarov"; Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://hovermind.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(rxAdapter) .build(); IBalanceService bs = retrofit.create(IBalanceService.class); Call<User> call = apiService.getUser(username); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { User user = response.body(); // update Activity/Fragment from here } @Override public void onFailure(Call<User> call, Throwable t) { // Log error here since request failed } }); }
BalanceActivity.java
public BalanceActivity extends Activity{ // BalanceRestClient will update some UI elements }
如何通过onResponse()更新活动/片段中的UI?
附加信息: 最小SDK:19个 目标SDK:23个 使用OkHttp和gson改造的2.1.0
public class BalanceRestClient { private static BalanceRestClient instance; private IBalanceService request; private BalanceRestClient() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://hovermind.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(rxAdapter) .build(); request = retrofit.create(IBalanceService.class); } public static synchronized BalanceRestClient getInstance() { if (instance == null) instance = new BalanceRestClient(); return instance; } public void getRequest(String userName, YourCustomeCallback callback) { Call<User> call = apiService.getUser(username); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { User user = response.body(); callback.onResponse(user); } @Override public void onFailure(Call<User> call, Throwable t) { // Log error here since request failed } }); } }