依赖注入服务

Abu*_*eji 8 android realm dagger-2

我想inject dependencies进入我的应用程序.一切都很好,直到我试着注入Realm我的Service班级.我开始得到IllegalStateException这显然是由我RealmThread它创建的访问引起的.所以,这是我的结构Dependency Injection

AppModule

@Module
public class AppModule {

    MainApplication mainApplication;

    public AppModule(MainApplication mainApplication) {
        this.mainApplication = mainApplication;
    }

    @Provides
    @Singleton
    MainApplication getFmnApplication() {
        return mainApplication;
    }
}
Run Code Online (Sandbox Code Playgroud)

RequestModule

@Module
public class RequestModule {

    @Provides
    @Singleton
    Retrofit.Builder getRetrofitBuilder() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.HOST)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(CustomGsonParser.returnCustomParser()));
    }

    @Provides
    @Singleton
    OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                .connectTimeout(30000, TimeUnit.SECONDS)
                .readTimeout(30000, TimeUnit.SECONDS).build();
    }

    @Provides
    @Singleton
    Retrofit getRetrofit() {
        return getRetrofitBuilder().client(getOkHttpClient()).build();
    }

    @Provides
    @Singleton
    ErrorUtils getErrorUtils() {
        return new ErrorUtils();
    }

    @Provides
    @Singleton
    MainAPI getMainAPI() {
        return getRetrofit().create(MainAPI.class);
    }

    // Used in the Service class
    @Provides
    @Singleton
    GeneralAPIHandler getGeneralAPIHandler(MainApplication mainApplication) {
        return new GeneralAPIHandler(mainApplication, getMainAPIHandler(), getErrorUtils());
    }
}
Run Code Online (Sandbox Code Playgroud)

AppComponent

@Singleton
@Component(modules = {
        AppModule.class,
        RequestModule.class
})
public interface MainAppComponent {

    void inject(SyncService suncService);
}
Run Code Online (Sandbox Code Playgroud)

应用程序类

public class MainApplication extends Application {

    private MainAppComponent mainAppComponent;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mainAppComponent = DaggerMainAppComponent.builder()
                .appModule(new AppModule(this))
                .requestModule(new RequestModule())
                .build();
    }

    public MainAppComponent getMainAppComponent() {
        return mainAppComponent;
    }
}
Run Code Online (Sandbox Code Playgroud)

GeneralAPIHandler

public class GeneralAPIHandler {

    private static final String TAG = "GeneralAPIHandler";
    private MainAPI mainAPI;
    private Realm realm;
    private ErrorUtils errorUtils;
    private Context context;

    public GeneralAPIHandler() {
    }

    public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
        this.mainAPI = mainAPI;
        this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext());
        this.errorUtils = errorUtils;
        this.context = mainApplication.getApplicationContext();
    }

    public void sendPayload(APIRequestListener apiRequestListener) {
        List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll(); <-- This is where the error comes from

        .... Other code here
    }
}
Run Code Online (Sandbox Code Playgroud)

这只发生在我从a调用它时Service class,它是用Application Context创建的.为什么要抛出一个IllegalStateException

服务类

public class SyncService extends IntentService {

    @Inject GeneralAPIHandler generalAPIHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        ((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public SyncService() {
        super("Sync");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        sendInformations();
    }

    private void sendInformations() {
        generalAPIHandler.sendPayload(new APIRequestListener() {
            @Override
            public void onError(APIError apiError){}

            @Override
            public void didComplete(WhichSync whichSync){}
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

在我做错了什么是使任何帮助Realm罚球IllegalStateException,将不胜感激.谢谢

Epi*_*rce 9

@Inject GeneralAPIHandler generalAPIHandler;

@Override
public void onCreate() {
    super.onCreate();
    ((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
}
Run Code Online (Sandbox Code Playgroud)

因此

public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
    this.mainAPI = mainAPI;
    this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext()); // <--
Run Code Online (Sandbox Code Playgroud)

此代码在UI线程上运行


@Override
protected void onHandleIntent(Intent intent) {
    sendInformations();
}

private void sendInformations() {
    generalAPIHandler.sendPayload(new APIRequestListener() {
    ....


public void sendPayload(APIRequestListener apiRequestListener) {
    List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll();
Run Code Online (Sandbox Code Playgroud)

此代码在IntentService后台线程上运行

你也不会关闭Realm实例,尽管它仍然是一个非循环的后台线程,所以它通过崩溃帮你一个忙.


解决方案,您应该获取Realm实例onHandleIntent(),并在finally {执行结束时关闭它.


你可能会说,"但是我将如何模拟我的构造函数参数",答案是使用类似的类

@Singleton
public class RealmFactory {
    @Inject
    public RealmFactory() {
    }

    public Realm create() {
        return Realm.getDefaultInstance();
    }
}
Run Code Online (Sandbox Code Playgroud)