2017-03-07 24 views
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); 
} 

感謝。

+0

您是否嘗試使用'BaseActivity extends AppCompatActivity'包含方法'subscribeToUser',之後'MainActivity'和其他活動擴展了BaseActivity。 –

+0

@RoShanShan如果我需要在活動之外使用'subscribeToUser()'方法,就像在一個適配器中一樣? – user7669706

+0

我認爲你可以在Activity中使用該方法並將結果發送到適配器。或者你可以發送'context'到你的適配器並使用((YouActivity)上下文).subscribeToUser()。 –

回答

2

在我看來,createService(ApiInterface.class)不應該被調用多次。這不是必要的,並會減慢你的應用程序。您可以嘗試創建一個單例模式UserService如下:

public class UserService { 

private UserService userService; 
final ApiInterface apiService; 
//Contructor private to prevent init object from outside directly. 
private UserService() { 
    apiService = ApiClient.createService(ApiInterface.class); 
} 
//use this method when you need to use UserService 
public static UserService getInstance() { 
    if(userService == null) { 
     userService = new UserService(); 
    } 
} 

// Used to subscribe to a user given their userId 
public void subscribeToUser(int userId, ServiceCallBack serviceCallBack) { 
    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(); 
       serviceCallBack.successful(response); 
      } else { 
       Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show(); 
      } 
     } 

     @Override 
     public void onFailure(Call<BasicResponse> call, Throwable t) { 
      Log.e(TAG, t.toString()); 
      serviceCallBack.fail(t); 
     } 
    }); 
} 
//this is callback interface, help you know whether success from outside. 
interface ServiceCallBack { 
    void successful(Response response); 
    void fail(Throwable t); 
} 
} 

如何使用:

UserService.getInstance(1, new ServiceCallBack(){ 

     @Override 
     public void successful(Response response) { 
      //process successful 
     } 

     @Override 
     public void fail(Throwable t) { 
      //process fail 
     } 
    }); 

現在你可以把所有的方法涉及到用戶的API UserService類重用。