我试图将单身经理添加到Android服务中。 问题是注入的管理器与ViewModel中的管理器不同。
Dagger组件
@Singleton
@Component(modules = {ApplicationModule.class, AppScreenModule.class, ServiceModule.class})
public interface AppComponent {
void inject(App application);
void inject(OpportunisticService opportunisticService);
@Component.Builder
interface Builder {
AppComponent build();
Builder applicationModule(ApplicationModule applicationModule);
}
}
模块
@Module
class ApplicationModule {
private final App mApp;
ApplicationModule(App app) {
mApp = app;
}
@Provides
@Named("ApplicationContext")
Context provideContext() {
return mApp.getApplicationContext();
}
@Provides
App provideApplication() {
return mApp;
}
@Provides
PeersManager providePeersManager() {
return new PeersManager();
}
}
@Module
abstract class ServiceModule {
@ContributesAndroidInjector
abstract OpportunisticService bindOpportunisticService();
}
初始化
public class Components {
private static AppComponent sComponent;
public static void initialize(App app) {
// Initialize the AppComponent
Preconditions.checkState(sComponent == null, "AppComponent already initialized");
sComponent = DaggerAppComponent.builder()
.applicationModule(new ApplicationModule(app))
.build();
}
public static AppComponent app() {
if (BuildConfig.DEBUG)
Preconditions.checkState(sComponent == null, "AppComponent not initialized");
return sComponent;
}
}
public class App extends Application implements HasActivityInjector, HasServiceInjector {
@Inject
DispatchingAndroidInjector<Activity> mActivityDispatchingAndroidInjector;
@Inject
DispatchingAndroidInjector<Service> mServiceDispatchingAndroidInjector;
@Override
public void onCreate() {
super.onCreate();
// Initialize the AppComponent
Components.initialize(this);
Components.app().inject(this);
}
@Override
public AndroidInjector<Activity> activityInjector() {
return mActivityDispatchingAndroidInjector;
}
@Override
public AndroidInjector<Service> serviceInjector() {
return mServiceDispatchingAndroidInjector;
}
}
声明PeerManager :
@Singleton
public class PeersManager {
@Inject
public PeersManager() {
}
}
使用PeersManager :
public class ViewModel {
private final PeersManager mPeersManager;
@Inject
public ViewModel (PeersManager peersManager) {
mPeersManager = peersManager;
}
}
public class OpportunisticService extends Service {
@Inject
PeersManager mPeersManager;
@Override
public void onCreate() {
super.onCreate();
AndroidInjection.inject(this);
}
}
问题是ViewModel.mPeersManager
与OpportunisticService.mPeersManager
不同,我认为PeersManager
被标记为单身时,它们会相同。
由于AndroidInjector
/ Activity
和Fragment
的{{1}}不同,我预计会发生这种情况。