如何使用Dagger在retrofit2 android中动态传递不同的URL

问题描述 投票:0回答:2
  1. ApplicationClass我通过一个网址,我在ActLogin.java使用它
  2. 现在我想传递ActUpcomingEvents另一个不同于ActLogin.java的网址
  3. 如何实现这一目标

net module.Java

@Module
public class NetModule {

    String mBaseUrl;
    Application mApplication;

    // Constructor needs one parameter to instantiate.
    public NetModule(String baseUrl, Application application) {
        this.mBaseUrl = baseUrl;
        this.mApplication = application;
    }

    // Dagger will only look for methods annotated with @Provides
    @Provides
    @Singleton
    // Application reference must come from AppModule.class
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }



    @Provides
    @Singleton
    Cache provideOkHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.cache(cache);
        client.addInterceptor(new RequestInterceptor(mApplication));
        client.readTimeout(Keys.READ_TIMEOUT, TimeUnit.SECONDS);
        client.connectTimeout(Keys.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
        client.writeTimeout(Keys.WRITE_TIMEOUT, TimeUnit.SECONDS);
        return client.build();
    }

    @Provides @Named("auth")
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
    }

}

app module.Java

@Module
public class AppModule {
    Application mApplication;

    public AppModule(Application mApplication) {
        this.mApplication = mApplication;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }
}

session module.Java

@Module
public class SessionModule {

    Application mApplication;

    public SessionModule(Application mApplication) {
        this.mApplication = mApplication;
    }

    @Provides
    @Singleton
    // Application reference must come from AppModule.class
    CaringSession providesCaringSession() {
        return new CaringSession(mApplication);
    }
}

net component.Java

@Singleton
@Component(modules = {AppModule.class,NetModule.class,SessionModule.class})
public interface NetComponent {
    void inject(ActUpcomingEvents activity);
    void inject(ActLogin activity);
}

ApplicationClass

public class CaringApp extends Application {

    static CaringApp appInstance;
    public static final String TAG = CaringApp.class.getSimpleName();
    private NetComponent mNetComponent;
    ANRWatchDog anrWatchDog = new ANRWatchDog(2000);
    private RxBus bus;

    private static CaringSession mSession;

    @Override
    public void onCreate() {
        super.onCreate();
        appInstance = this;
        mSession = new CaringSession(appInstance);
        //Initialize the crashlytics
        initCrashlytics();
        //Initialize the watch dog
        initAnrWatchDog();
        //Initialize retrofit
        retrofitInit();
        //Rx Bus Init
    }



    public RxBus getBus() {
        return bus;
    }

    private void initAnrWatchDog() {
        anrWatchDog.setANRListener(new ANRWatchDog.ANRListener() {
            @Override
            public void onAppNotResponding(ANRError error) {
                Log.e("ANR-Watchdog", "Detected Application Not Responding!");

                // Some tools like ACRA are serializing the exception, so we must make sure the exception serializes correctly
                try {
                    new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(error);
                }
                catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                Crashlytics.logException(new RuntimeException(error.getStackTrace().toString()));
                Crashlytics.log(Log.ERROR, "ANR-LOG", error.getStackTrace().toString());
                Log.i("ANR-Watchdog", "Error was successfully serialized");

                throw error;
            }
        });

        anrWatchDog.start();
    }


    /**************** Init  ****************/
    /** Init retrofit **/
    private void retrofitInit() {
        try{
            mNetComponent = DaggerNetComponent.builder()
                    .appModule(new AppModule(this))
                    .netModule(new NetModule(Keys.BASE_URL,this))
                    .sessionModule(new SessionModule(getAppInstance()))
                    .build();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    /** Init crashlytics **/
    private void initCrashlytics() {
        Fabric.with(this, new Crashlytics());
    }
    /**************** Init  ****************/


    /**************** Getters ****************/
    /** Net component **/
    public NetComponent getNetComponent() {
        return mNetComponent;
    }

    /** App Instance **/
    public static CaringApp getAppInstance() {
        if (appInstance == null) {
            appInstance = new CaringApp();
        }
        return appInstance;
    }

    public static CaringSession getmSession() {
        return mSession;
    }
    /**************** Getters ****************/

在我的kotlinClass中,我正在注射

class ActLogin : AppCompatActivity(), IntDataLogin {

 @set:Inject var retrofit: Retrofit? = null

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (application as CaringApp).netComponent.inject(this)
    }

}
android retrofit2 dagger
2个回答
0
投票

如果你的意思是,你有另一个基本网址。你可以做这样的事;

public interface YourAPIInterface {

    @GET
    Call<POJO> doAllItems(@Url String url);

}

@Url对参数的注释,以允许动态指定完整的主机名。然后你可以在Refrofit中以正常方式调用它


0
投票

不幸的是,改造(当前版本2.5.0)必须使用baseUrl初始化,之后无法更改。但是,在您的接口端点定义中,您可以传递@Url带注释的参数(请参阅Nanda Z的上一个答案),或者您可以创建多个Retrofit实例(使用不同的baseUrl,使用@Named注释),这将由Dagger提供。例如:

@Provides
@Named("myCoolRetrofitInstance1")
@Singleton
Retrofit provideRetrofit1(Gson gson, OkHttpClient okHttpClient) {
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(SOME_URL_1)
            .client(okHttpClient)
            .build();
    return retrofit;
}

@Provides
@Named("myCoolRetrofitInstance2")
@Singleton
Retrofit provideRetrofit2(Gson gson, OkHttpClient okHttpClient) {
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(SOME_URL_2)
            .client(okHttpClient)
            .build();
    return retrofit;
}

对于注入,您还必须使用正确的@Named注释。

@Inject
@Named("myCoolRetrofitInstance1") // or @Named("myCoolRetrofitInstance2")
lateinit var retforit: Retforit
© www.soinside.com 2019 - 2024. All rights reserved.