gpt4 book ai didi

android - 服务中的依赖注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:00 39 4
gpt4 key购买 nike

我正在尝试注入(inject)依赖项到我的应用程序中。一切正常,直到我尝试将 Realm 注入(inject)我的 Service 类。我开始收到 IllegalStateException,这显然是由于我从创建的 Thread 访问 Realm 引起的。所以,这是我的 Dependency Injection

的结构

AppModule

@Module
public class AppModule {

MainApplication mainApplication;

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

@Provides
@Singleton
MainApplication getFmnApplication() {
return mainApplication;
}
}

请求模块

@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());
}
}

AppComponent

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

void inject(SyncService suncService);
}

应用类

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;
}
}

通用API处理程序

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
}
}

只有当我从 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){}
})
}
}

任何关于我做错了什么使 Realm 抛出 IllegalStateException 的帮助将不胜感激。谢谢

最佳答案

@Inject GeneralAPIHandler generalAPIHandler;

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

因此

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

此代码在 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();

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

尽管处于非循环后台线程中,您也不会关闭 Realm 实例,所以它通过崩溃帮了您一个忙。


解决方法,应该在onHandleIntent()中获取Realm实例,并在执行结束时在finally{中关闭。


你可能会说,“但是我将如何模拟我的构造函数参数”,答案是使用像这样的类

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

public Realm create() {
return Realm.getDefaultInstance();
}
}

关于android - 服务中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754527/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com